@runtypelabs/persona 4.9.0 → 4.10.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 Im=Object.create;var La=Object.defineProperty;var Wm=Object.getOwnPropertyDescriptor;var Hm=Object.getOwnPropertyNames;var Bm=Object.getPrototypeOf,Dm=Object.prototype.hasOwnProperty;var wr=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pa=(e,t)=>{for(var n in t)La(e,n,{get:t[n],enumerable:!0})},lp=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Hm(t))!Dm.call(e,s)&&s!==n&&La(e,s,{get:()=>t[s],enumerable:!(o=Wm(t,s))||o.enumerable});return e};var Cs=(e,t,n)=>(n=e!=null?Im(Bm(e)):{},lp(t||!e||!e.__esModule?La(n,"default",{value:e,enumerable:!0}):n,e)),Om=e=>lp(La({},"__esModule",{value:!0}),e);var pp={};Pa(pp,{DOMPurify:()=>dp.default,Marked:()=>cp.Marked});var cp,dp,up=wr(()=>{"use strict";cp=require("marked"),dp=Cs(require("dompurify"),1)});var Ir,Jl=wr(()=>{"use strict";Ir=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 s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let 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 s=n.createBufferSource();s.buffer=o,s.connect(n.destination);let r=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=r:this.nextStartTime<r&&(this.nextStartTime=r,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let r=0;r<n;r++){let a=s.getInt16(r*2,!0);o[r]=a/32768}return o}}});function $h(e){return e.replace(/\/+$/,"")}async function jh(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 Za,pu=wr(()=>{"use strict";Jl();Za=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 Ir(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 s=await this.ensurePlayer();if(t!==this.generation)return;s.flush(),s.resume(),s.onStarted(()=>{t===this.generation&&o.onStart?.()}),s.onFinished(()=>{t===this.generation&&o.onEnd?.()});let r=`${$h(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(r,{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 jh(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&&s.enqueue(d)}s.markStreamEnd()}catch(s){if(t!==this.generation)return;let r=s instanceof Error?s:new Error(String(s));this.opts.onError?.(r),o.onError?.(r)}}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 ei,uu=wr(()=>{"use strict";ei=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:s=>{if(o){n.onError?.(s);return}this.options.onFallback?.(s),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 fu={};Pa(fu,{FallbackSpeechEngine:()=>ei,RuntypeSpeechEngine:()=>Za});var gu=wr(()=>{"use strict";pu();uu()});var hu={};Pa(hu,{createReconnectController:()=>zh});function zh(e){let t=0,n=null,o=null,s=!1,r=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},a=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||r()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{s||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),s=!0)},c=()=>{s&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),s=!1)},u=h=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},h)}),y=()=>{let h=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 M=e.buildErrorContent("Connection lost and the response could not be resumed.");M?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:M,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."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Uh,C=e.config.reconnect?.maxAttempts??h.length,M=e.config.reconnectStream;if(!M){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let P=e.getResumable(),I=P.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:P,attempt:t});let W=null;try{let $=await M({executionId:P.executionId,after:P.lastEventId,signal:A.signal});$&&$.ok&&$.body&&(W=$.body)}catch{W=null}if(A.signal.aborted)return;if(W){let $=e.getMessages().find(w=>w.id===P.assistantMessageId)?.content,N=typeof $=="string"?$:"";try{await e.resumeConnect(W,P.assistantMessageId,N)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:P});return}e.getResumable().lastEventId!==I&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:r}}var Uh,yu=wr(()=>{"use strict";Uh=[1e3,2e3,4e3,8e3,8e3]});var ux={};Pa(ux,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Vl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ql,ASK_USER_QUESTION_TOOL_NAME:()=>Ts,AgentWidgetClient:()=>Yo,AgentWidgetSession:()=>Hr,AttachmentManager:()=>tr,BrowserSpeechEngine:()=>xo,DEFAULT_COMPONENTS:()=>nc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ni,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>cn,DEFAULT_PALETTE:()=>ec,DEFAULT_SEMANTIC:()=>tc,DEFAULT_WIDGET_CONFIG:()=>ut,PRESETS:()=>Xc,PRESET_FULLSCREEN:()=>Jc,PRESET_MINIMAL:()=>Gc,PRESET_SHOP:()=>Kc,ReadAloudController:()=>er,SUGGEST_REPLIES_CLIENT_TOOL:()=>Na,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>jl,SUGGEST_REPLIES_TOOL_NAME:()=>Tn,THEME_ZONES:()=>Pu,VERSION:()=>hn,WEBMCP_TOOL_PREFIX:()=>Sn,WebMcpBridge:()=>Er,accessibilityPlugin:()=>vg,animationsPlugin:()=>xg,applyThemeVariables:()=>nr,attachHeaderToContainer:()=>rr,brandPlugin:()=>Cg,buildComposer:()=>jr,buildDefaultHeader:()=>mc,buildHeader:()=>Xn,buildHeaderWithLayout:()=>$r,buildMinimalHeader:()=>hc,builtInClientToolsForDispatch:()=>Pr,collectEnrichedPageContext:()=>yg,componentRegistry:()=>En,createActionManager:()=>ea,createAgentExperience:()=>zi,createAskUserQuestionBubble:()=>qp,createBestAvailableVoiceProvider:()=>Ya,createBubbleWithLayout:()=>Af,createCSATFeedback:()=>$i,createComboButton:()=>ui,createComponentMiddleware:()=>Gf,createComponentStreamParser:()=>Ni,createDefaultSanitizer:()=>Bl,createDemoCarousel:()=>_g,createDirectivePostprocessor:()=>xp,createDropdownMenu:()=>To,createFlexibleJsonStreamParser:()=>Jp,createIconButton:()=>mt,createImagePart:()=>nu,createJsonStreamParser:()=>Va,createLabelButton:()=>Gn,createLocalStorageAdapter:()=>Oi,createMarkdownProcessor:()=>ws,createMarkdownProcessorFromConfig:()=>Jo,createMessageActions:()=>Ac,createNPSFeedback:()=>ji,createPlainTextParser:()=>za,createPlugin:()=>Sg,createRegexJsonParser:()=>qa,createRovingTablist:()=>Di,createSlashCommandsSource:()=>ag,createStandardBubble:()=>Ur,createStaticMentionSource:()=>sg,createTextPart:()=>bo,createTheme:()=>Br,createThemeObserver:()=>Dr,createToggleGroup:()=>Jn,createTypingIndicator:()=>sr,createVoiceProvider:()=>vo,createWidgetHostLayout:()=>na,createXmlParser:()=>Ka,default:()=>Mg,defaultActionHandlers:()=>cr,defaultJsonActionParser:()=>Zs,defaultMentionFilter:()=>Vi,defaultParseRules:()=>qc,detectColorScheme:()=>Ds,directivePostprocessor:()=>Cp,ensureAskUserQuestionSheet:()=>Lr,escapeHtml:()=>Rn,extractComponentDirectiveFromMessage:()=>_i,fileToImagePart:()=>ou,formatEnrichedContext:()=>bg,generateAssistantMessageId:()=>yo,generateCodeSnippet:()=>Wg,generateMessageId:()=>Yp,generateStableSelector:()=>Vc,generateUserMessageId:()=>Rr,getActiveTheme:()=>Co,getColorScheme:()=>li,getDisplayText:()=>eu,getHeaderLayout:()=>yc,getImageParts:()=>tu,getPreset:()=>Eg,hasComponentDirective:()=>ta,hasImages:()=>Xa,headerLayouts:()=>Ei,highContrastPlugin:()=>Ag,initAgentWidget:()=>$c,isAskUserQuestionMessage:()=>zn,isComponentDirectiveType:()=>Kf,isDockedMountMode:()=>Wt,isSuggestRepliesMessage:()=>Ms,isVoiceSupported:()=>Is,isWebMcpToolName:()=>po,latestAgentSuggestions:()=>Fa,listRegisteredStreamAnimations:()=>uf,loadMarkdownParsers:()=>Wl,markdownPostprocessor:()=>Hl,mergeWithDefaults:()=>oi,normalizeContent:()=>Zp,onMarkdownParsersReady:()=>Sr,parseAskUserQuestionPayload:()=>qn,parseSuggestRepliesPayload:()=>zl,pickBestVoice:()=>Wr,pluginRegistry:()=>Ys,reducedMotionPlugin:()=>wg,registerStreamAnimationPlugin:()=>df,removeAskUserQuestionSheet:()=>go,renderComponentDirective:()=>Fi,renderLoadingIndicatorWithFallback:()=>wc,renderLucideIcon:()=>oe,resolveDockConfig:()=>tn,resolveSanitizer:()=>Tr,resolveTokens:()=>ai,stripWebMcpPrefix:()=>Wa,themeToCssVariables:()=>ii,unregisterStreamAnimationPlugin:()=>pf,validateImageFile:()=>ru,validateTheme:()=>oc});module.exports=Om(ux);var mp=require("marked"),hp=Cs(require("dompurify"),1);var Ar=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,s=null,r=null;return{setLoader:c=>{o=c,n&&(s=null,r=null)},load:()=>s?Promise.resolve(s):r||(r=(o??t)().then(u=>(s=u,u)).catch(u=>{throw r=null,u}),r),provide:c=>{s=c},getSync:()=>s}};var{setLoader:vx,load:Nm,provide:Fm,getSync:Il}=Ar({fallbackImport:()=>Promise.resolve().then(()=>(up(),pp))}),Ra=new Set,fp=()=>{let e=[...Ra];Ra.clear();for(let t of e)try{t()}catch{}};var Wl=()=>{let e=Il();return e?Promise.resolve(e):Nm().then(t=>(fp(),t))},Sr=e=>Il()?()=>{}:(Ra.add(e),Wl().catch(()=>{}),()=>{Ra.delete(e)}),gp=e=>{Fm(e),fp()},jn=Il;gp({Marked:mp.Marked,DOMPurify:hp.default});var _m=e=>{if(e)return e},ws=e=>{let t=null;return n=>{let o=jn();if(!o)return Rn(n);if(!t){let{Marked:s}=o,r=e?.markedOptions;t=new s({gfm:r?.gfm??!0,breaks:r?.breaks??!0,pedantic:r?.pedantic,silent:r?.silent});let a=_m(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Jo=e=>e?ws({markedOptions:e.options,renderer:e.renderer}):ws(),$m=ws(),Hl=e=>$m(e),Rn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),bp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),yp=e=>`%%FORM_PLACEHOLDER_${e}%%`,vp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,s)=>{try{let r=JSON.parse(s.trim());if(r&&typeof r=="object"&&r.component==="form"&&r.type){let a=yp(t.length);return t.push({token:a,type:String(r.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,s)=>{let r=yp(t.length);return t.push({token:r,type:s}),r}),n},xp=e=>{let t=Jo(e);return n=>{let o=[],s=vp(n,o),r=t(s);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${bp(i)}"></div>`;r=r.replace(p,c)}),r}},Cp=e=>{let t=[],n=vp(e,t),o=Hl(n);return t.forEach(({token:s,type:r})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${bp(r)}"></div>`;o=o.replace(a,p)}),o};var jm={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"]},Um=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Bl=()=>{let e=null;return t=>{let n=jn();if(!n)return Rn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(s,r)=>{if(r.attrName==="src"||r.attrName==="href"){let a=r.attrValue;a.toLowerCase().startsWith("data:")&&!Um.test(a)&&(r.attrValue="",r.keepAttr=!1)}})}return e.sanitize(t,jm)}},Tr=e=>e===!1?null:typeof e=="function"?e:Bl();var wp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ap=e=>e.includes("|"),Sp=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(" | ")} |`,qm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Vm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Tp=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let o=0;o<t.length-1;o++){let s=t[o],r=t[o+1];if(!Ap(s)||wp.test(s)||!wp.test(r))continue;let a=Sp(s).length;if(a<1)continue;let i=qm(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()===""||!Ap(d))break;let c=zm(Vm(Sp(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
- `):e};var Sn="webmcp:",Dl=new Map,Ep=e=>{Dl.clear();for(let t of e){let n=t.title?.trim();n&&Dl.set(t.name,n)}},As=e=>Dl.get(Wa(e)),Ia={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Mp=null;function Lp(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}:${Km(t.join(""))}`}function kp(e,t){let n=3735928559^t,o=1103547991^t;for(let s=0;s<e.length;s++){let r=e.charCodeAt(s);n=Math.imul(n^r,2654435761),o=Math.imul(o^r,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 Km(e){let t=kp(e,0).toString(36),n=kp(e,2654435761).toString(36);return`${t}.${n}`}var Er=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(s){return Ia.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}Ep(n);let o=typeof location<"u"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let r={name:s.name,description:s.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Jm(s.inputSchema);return a&&(r.parametersSchema=a),r})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return An("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let h=typeof document<"u"&&!!document.modelContext;return An(h?"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 r=Wa(t),a;try{a=await s.getTools()}catch(h){let C=h instanceof Error?h.message:String(h);return An(`Failed to read WebMCP registry: ${C}`)}Ep(a);let i=a.find(h=>h.name===r);if(!i)return An(`WebMCP tool not registered on this page: ${r}`);if(!this.passesClientAllowlist(r))return An(`WebMCP tool not allowed by client allowlist: ${r}`);if(o?.aborted)return An("Aborted by cancel()");let p=As(r),d={toolName:r,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return An("User declined the tool call.");if(o?.aborted)return An("Aborted by cancel()");let c=new AbortController,u=!1,y=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await s.executeTool(i,Zm(n),{signal:c.signal});return Xm(h)}catch(h){if(u)return An(`WebMCP tool '${r}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return An("Aborted by cancel()");let C=h instanceof Error?h.message:String(h);return An(C)}finally{clearTimeout(y),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Mp?await Mp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ia.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,Ia.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??Qm;try{return await n(t)}catch(o){return Ia.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=>Gm(t,o))}},Wa=e=>e.startsWith(Sn)?e.slice(Sn.length):e,po=e=>e.startsWith(Sn),Gm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Jm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Xm=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:eh(t)}]}},An=e=>({isError:!0,content:[{type:"text",text:e}]}),Qm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Ym(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var Bm=Object.create;var Pa=Object.defineProperty;var Dm=Object.getOwnPropertyDescriptor;var Om=Object.getOwnPropertyNames;var Nm=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var wr=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ra=(e,t)=>{for(var n in t)Pa(e,n,{get:t[n],enumerable:!0})},cp=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Om(t))!Fm.call(e,r)&&r!==n&&Pa(e,r,{get:()=>t[r],enumerable:!(o=Dm(t,r))||o.enumerable});return e};var Cs=(e,t,n)=>(n=e!=null?Bm(Nm(e)):{},cp(t||!e||!e.__esModule?Pa(n,"default",{value:e,enumerable:!0}):n,e)),_m=e=>cp(Pa({},"__esModule",{value:!0}),e);var up={};Ra(up,{DOMPurify:()=>pp.default,Marked:()=>dp.Marked});var dp,pp,fp=wr(()=>{"use strict";dp=require("marked"),pp=Cs(require("dompurify"),1)});var Ir,Xl=wr(()=>{"use strict";Ir=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 zh(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 ei,uu=wr(()=>{"use strict";Xl();ei=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 Ir(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=`${zh(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 ti,fu=wr(()=>{"use strict";ti=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 gu={};Ra(gu,{FallbackSpeechEngine:()=>ti,RuntypeSpeechEngine:()=>ei});var mu=wr(()=>{"use strict";uu();fu()});var yu={};Ra(yu,{createReconnectController:()=>Kh});function Kh(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},a=()=>{let h=e.getStatus();h!=="resuming"&&h!=="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=h=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},h)}),y=()=>{let h=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 M=e.buildErrorContent("Connection lost and the response could not be resumed.");M?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:M,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."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Vh,C=e.config.reconnect?.maxAttempts??h.length,M=e.config.reconnectStream;if(!M){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let P=e.getResumable(),I=P.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:P,attempt:t});let W=null;try{let $=await M({executionId:P.executionId,after:P.lastEventId,signal:A.signal});$&&$.ok&&$.body&&(W=$.body)}catch{W=null}if(A.signal.aborted)return;if(W){let $=e.getMessages().find(w=>w.id===P.assistantMessageId)?.content,N=typeof $=="string"?$:"";try{await e.resumeConnect(W,P.assistantMessageId,N)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:P});return}e.getResumable().lastEventId!==I&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var Vh,bu=wr(()=>{"use strict";Vh=[1e3,2e3,4e3,8e3,8e3]});var hx={};Ra(hx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Kl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Vl,ASK_USER_QUESTION_TOOL_NAME:()=>Ts,AgentWidgetClient:()=>Yo,AgentWidgetSession:()=>Hr,AttachmentManager:()=>tr,BrowserSpeechEngine:()=>xo,DEFAULT_COMPONENTS:()=>oc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>oi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>ln,DEFAULT_PALETTE:()=>tc,DEFAULT_SEMANTIC:()=>nc,DEFAULT_WIDGET_CONFIG:()=>dt,PRESETS:()=>Qc,PRESET_FULLSCREEN:()=>Xc,PRESET_MINIMAL:()=>Jc,PRESET_SHOP:()=>Gc,ReadAloudController:()=>er,SUGGEST_REPLIES_CLIENT_TOOL:()=>Fa,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Ul,SUGGEST_REPLIES_TOOL_NAME:()=>Tn,THEME_ZONES:()=>Ru,VERSION:()=>mn,WEBMCP_TOOL_PREFIX:()=>Sn,WebMcpBridge:()=>Er,accessibilityPlugin:()=>wg,animationsPlugin:()=>Ag,applyThemeVariables:()=>nr,attachHeaderToContainer:()=>rr,brandPlugin:()=>Sg,buildComposer:()=>jr,buildDefaultHeader:()=>hc,buildHeader:()=>Xn,buildHeaderWithLayout:()=>$r,buildMinimalHeader:()=>yc,builtInClientToolsForDispatch:()=>Pr,collectEnrichedPageContext:()=>xg,componentRegistry:()=>En,createActionManager:()=>ta,createAgentExperience:()=>qi,createAskUserQuestionBubble:()=>Vp,createBestAvailableVoiceProvider:()=>Za,createBubbleWithLayout:()=>Sf,createCSATFeedback:()=>ji,createComboButton:()=>ui,createComponentMiddleware:()=>Qf,createComponentStreamParser:()=>Fi,createDefaultSanitizer:()=>Dl,createDemoCarousel:()=>Ug,createDirectivePostprocessor:()=>Cp,createDropdownMenu:()=>To,createFlexibleJsonStreamParser:()=>Xp,createIconButton:()=>gt,createImagePart:()=>ou,createJsonStreamParser:()=>Ka,createLabelButton:()=>Gn,createLocalStorageAdapter:()=>Ni,createMarkdownProcessor:()=>ws,createMarkdownProcessorFromConfig:()=>Jo,createMessageActions:()=>Sc,createNPSFeedback:()=>Ui,createPlainTextParser:()=>qa,createPlugin:()=>Mg,createRegexJsonParser:()=>Va,createRovingTablist:()=>Di,createSlashCommandsSource:()=>cg,createStandardBubble:()=>Ur,createStaticMentionSource:()=>lg,createTextPart:()=>bo,createTheme:()=>Ds,createThemeObserver:()=>Dr,createToggleGroup:()=>Jn,createTypingIndicator:()=>sr,createVoiceProvider:()=>vo,createWidgetHostLayout:()=>oa,createXmlParser:()=>Ga,default:()=>Pg,defaultActionHandlers:()=>cr,defaultJsonActionParser:()=>ea,defaultMentionFilter:()=>Ki,defaultParseRules:()=>Vc,detectColorScheme:()=>Os,directivePostprocessor:()=>wp,ensureAskUserQuestionSheet:()=>Lr,escapeHtml:()=>Rn,extractComponentDirectiveFromMessage:()=>$i,fileToImagePart:()=>ru,formatEnrichedContext:()=>Cg,generateAssistantMessageId:()=>yo,generateCodeSnippet:()=>Dg,generateMessageId:()=>Zp,generateStableSelector:()=>Kc,generateUserMessageId:()=>Rr,getActiveTheme:()=>Co,getColorScheme:()=>li,getDisplayText:()=>tu,getHeaderLayout:()=>bc,getImageParts:()=>nu,getPreset:()=>Lg,hasComponentDirective:()=>na,hasImages:()=>Qa,headerLayouts:()=>Ei,highContrastPlugin:()=>Eg,initAgentWidget:()=>jc,isAskUserQuestionMessage:()=>zn,isComponentDirectiveType:()=>Xf,isDockedMountMode:()=>It,isSuggestRepliesMessage:()=>Ms,isVoiceSupported:()=>Is,isWebMcpToolName:()=>po,latestAgentSuggestions:()=>_a,listRegisteredStreamAnimations:()=>ff,loadMarkdownParsers:()=>Hl,markdownPostprocessor:()=>Bl,mergeWithDefaults:()=>Br,normalizeContent:()=>eu,onMarkdownParsersReady:()=>Sr,parseAskUserQuestionPayload:()=>qn,parseSuggestRepliesPayload:()=>ql,pickBestVoice:()=>Wr,pluginRegistry:()=>Zs,reducedMotionPlugin:()=>Tg,registerStreamAnimationPlugin:()=>pf,removeAskUserQuestionSheet:()=>go,renderComponentDirective:()=>_i,renderLoadingIndicatorWithFallback:()=>Ac,renderLucideIcon:()=>ne,resolveDockConfig:()=>en,resolveSanitizer:()=>Tr,resolveTokens:()=>ai,stripWebMcpPrefix:()=>Ha,themeToCssVariables:()=>ii,unregisterStreamAnimationPlugin:()=>uf,validateImageFile:()=>su,validateTheme:()=>rc});module.exports=_m(hx);var hp=require("marked"),yp=Cs(require("dompurify"),1);var Ar=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:Ax,load:$m,provide:jm,getSync:Wl}=Ar({fallbackImport:()=>Promise.resolve().then(()=>(fp(),up))}),Ia=new Set,gp=()=>{let e=[...Ia];Ia.clear();for(let t of e)try{t()}catch{}};var Hl=()=>{let e=Wl();return e?Promise.resolve(e):$m().then(t=>(gp(),t))},Sr=e=>Wl()?()=>{}:(Ia.add(e),Hl().catch(()=>{}),()=>{Ia.delete(e)}),mp=e=>{jm(e),gp()},jn=Wl;mp({Marked:hp.Marked,DOMPurify:yp.default});var Um=e=>{if(e)return e},ws=e=>{let t=null;return n=>{let o=jn();if(!o)return Rn(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=Um(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Jo=e=>e?ws({markedOptions:e.options,renderer:e.renderer}):ws(),zm=ws(),Bl=e=>zm(e),Rn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),vp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),bp=e=>`%%FORM_PLACEHOLDER_${e}%%`,xp=(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=bp(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=bp(t.length);return t.push({token:s,type:r}),s}),n},Cp=e=>{let t=Jo(e);return n=>{let o=[],r=xp(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="${vp(i)}"></div>`;s=s.replace(p,c)}),s}},wp=e=>{let t=[],n=xp(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="${vp(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"]},Vm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Dl=()=>{let e=null;return t=>{let n=jn();if(!n)return Rn(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:")&&!Vm.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,qm)}},Tr=e=>e===!1?null:typeof e=="function"?e:Dl();var Ap=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Sp=e=>e.includes("|"),Tp=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())},Km=e=>`| ${e.join(" | ")} |`,Gm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Jm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ep=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(!Sp(r)||Ap.test(r)||!Ap.test(s))continue;let a=Tp(r).length;if(a<1)continue;let i=Gm(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()===""||!Sp(d))break;let c=Km(Jm(Tp(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
+ `):e};var Sn="webmcp:",Ol=new Map,Mp=e=>{Ol.clear();for(let t of e){let n=t.title?.trim();n&&Ol.set(t.name,n)}},As=e=>Ol.get(Ha(e)),Wa={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},kp=null;function Pp(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}:${Xm(t.join(""))}`}function Lp(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 Xm(e){let t=Lp(e,0).toString(36),n=Lp(e,2654435761).toString(36);return`${t}.${n}`}var Er=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 Wa.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Mp(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=Ym(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return An("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return An(h?"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=Ha(t),a;try{a=await r.getTools()}catch(h){let C=h instanceof Error?h.message:String(h);return An(`Failed to read WebMCP registry: ${C}`)}Mp(a);let i=a.find(h=>h.name===s);if(!i)return An(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return An(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return An("Aborted by cancel()");let p=As(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return An("User declined the tool call.");if(o?.aborted)return An("Aborted by cancel()");let c=new AbortController,u=!1,y=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await r.executeTool(i,nh(n),{signal:c.signal});return Zm(h)}catch(h){if(u)return An(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return An("Aborted by cancel()");let C=h instanceof Error?h.message:String(h);return An(C)}finally{clearTimeout(y),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(kp?await kp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Wa.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,Wa.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??eh;try{return await n(t)}catch(o){return Wa.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=>Qm(t,o))}},Ha=e=>e.startsWith(Sn)?e.slice(Sn.length):e,po=e=>e.startsWith(Sn),Qm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ym=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Zm=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:oh(t)}]}},An=e=>({isError:!0,content:[{type:"text",text:e}]}),eh=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=th(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)},Ym=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)}},Zm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},eh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Xo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ha(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 th="agent_",nh="flow_";function Pp(e){return e.startsWith(th)?{kind:"agentId",agentId:e}:e.startsWith(nh)?{kind:"flowId",flowId:e}:null}function Rp(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=Pp(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 s=Pp(n);if(s)return s;let r=t?.default;if(r)return{kind:"payload",payload:r(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},In=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Ip=()=>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[r,a]of Object.entries(t.attrs))o.setAttribute(r,a);if(t.style){let r=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(r[i]=p)}}let s=n.filter(r=>r!=null);return s.length>0&&o.append(...s),o},Un=(...e)=>e.filter(Boolean).join(" ");var Ts="ask_user_question",Ss=8,Mr="data-persona-ask-sheet-for",oh="Other",rh="Other\u2026",Hp="Type your own answer here",Bp="Send",sh="Next",ah="Back",ih="Submit all",lh="Skip",ch=3,Ol="data-ask-current-index",Nl="data-ask-question-count",Dp="data-ask-answers",Fl="data-ask-grouped",Op="data-ask-layout",dh=e=>e.layout==="pills"?"pills":"rows",ph=e=>e.getAttribute(Op)==="pills"?"pills":"rows",Wp=!1,Np=e=>e.replace(/["\\]/g,"\\$&"),zn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ts,Ba=e=>e?.features?.askUserQuestion??{},qn=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 s=o.join(""),r=(0,uo.parse)(s,uo.STR|uo.OBJ|uo.ARR);if(r&&typeof r=="object")return{payload:r,complete:n}}catch{}return{payload:null,complete:n}},Es=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ss&&!Wp&&(Wp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ss}.`)),t.slice(0,Ss)},uh=e=>Es(e)[0]??null,fh=(e,t)=>Es(e)[t]??null,Fp=(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))},_p=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let s=m("span","persona-ask-row-check");o.appendChild(s)}else{let s=m("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},gh=(e,t,n,o)=>{let r=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(r.type="button",r.setAttribute("role",o?"checkbox":"button"),r.setAttribute("aria-pressed","false"),r.setAttribute("data-ask-user-action","pick"),r.setAttribute("data-option-index",String(t)),r.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)}r.appendChild(a);let p=_p(n,o,t);p&&r.appendChild(p)}else r.textContent=e.label,e.description&&(r.title=e.description);return r},mh=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},hh=(e,t,n,o)=>{let r=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");r.setAttribute("role","group"),r.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<ch;c++)r.appendChild(mh(o));return r}if(p.forEach((c,u)=>{r.appendChild(gh(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?oh:rh;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 y=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Hp,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),y.appendChild(f),u.appendChild(y);let h=_p(o,a,p.length);h&&u.appendChild(h),r.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,r.appendChild(u)}}return r},$p=(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 s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=e.freeTextPlaceholder??Hp,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),t!=="rows"){let r=m("button","persona-ask-free-text-submit persona-pointer-events-auto");r.type="button",r.textContent=e.submitLabel??Bp,r.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(r)}return o},yh=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??Bp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},bh=(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 s=m("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??ah,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,o.appendChild(s);let r=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??lh,a.setAttribute("data-ask-user-action","skip"),r.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??ih:n.nextLabel??sh,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,r.appendChild(i),o.appendChild(r),o},Qo=e=>{let t=e.getAttribute(Dp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},jp=(e,t)=>{e.setAttribute(Dp,JSON.stringify(t))},mn=e=>{let t=Number(e.getAttribute(Ol)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},vh=(e,t)=>{e.setAttribute(Ol,String(Math.max(0,Math.floor(t))))},kr=e=>{let t=Number(e.getAttribute(Nl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},fo=e=>e.getAttribute(Fl)==="true",xh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,r)=>{let a=typeof s?.question=="string"?s.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[r]=i)}}),o},Ch=(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)))},Da=(e,t)=>{let{payload:n}=qn(t),o=Es(n),s=Qo(e),r={},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(s,p)&&(r[d]=s[p]))}),r},Up=e=>{let t=Qo(e),n=mn(e),o=t[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(p=>s.add(p));let r=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');r.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=s.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(r).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="")},zp=e=>{if(!fo(e))return;let t=Qo(e),n=mn(e),o=t[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,r=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');r&&(r.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},_l=(e,t,n)=>{let o=Ba(n),s=ph(e),{payload:r,complete:a}=qn(t),i=fo(e),p=mn(e),d=kr(e),c=i?fh(r,p):uh(r),u=!!c?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let I=typeof c?.question=="string"?c.question:"";h.textContent=I,h.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let I=hh(c,o,a,s);C.replaceWith(I)}if(s!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith($p(o,s))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(yh(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=bh(p,d,o);P?P.replaceWith(I):e.appendChild(I)}else P&&P.remove();Up(e),zp(e)},wh=(e,t,n)=>{let o=Ba(t),s=dh(o),r=e.toolCall.id,a=Es(n),i=Math.max(1,a.length),p=i>1,d=xh(e,a),c=p?Ch(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Mr,r),u.setAttribute("data-tool-call-id",r),u.setAttribute("data-message-id",e.id),u.setAttribute(Nl,String(i)),u.setAttribute(Ol,String(c)),u.setAttribute(Fl,p?"true":"false"),u.setAttribute(Op,s),jp(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`),Fp(u,o);let y=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",y.appendChild(f);let h=m("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",y.appendChild(h),u.appendChild(y);let M=m("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),s!=="rows"&&u.appendChild($p(o,s)),_l(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ah=(e,t,n)=>{let{payload:o}=qn(t),s=Math.max(1,Es(o).length);s>kr(e)&&(e.setAttribute(Nl,String(s)),s>1&&!fo(e)&&e.setAttribute(Fl,"true")),_l(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=Ba(t);Fp(n,o);let s=m("span","persona-ask-stub-label"),{complete:r}=qn(e);return s.textContent=r?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Lr=(e,t,n)=>{if(!n||!zn(e)||Ba(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${Mr}]`).forEach(d=>{d.getAttribute(Mr)!==s&&d.remove()});let a=n.querySelector(`[${Mr}="${Np(s)}"]`);if(a){Ah(a,e,t);return}let{payload:i}=qn(e),p=wh(e,t,i);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${Mr}="${Np(t)}"]`:`[${Mr}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let r=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(r)?r: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=Qo(e),o=mn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,jp(e,n),Up(e),zp(e)},Oa=(e,t,n,o)=>{let s=kr(e),r=Math.max(0,Math.min(s-1,o));vh(e,r),_l(e,t,n)};var Tn="suggest_replies";var jl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Na={name:Tn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:jl,origin:"sdk",annotations:{readOnlyHint:!0}},Ul=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ms=e=>e.variant==="tool"&&e.toolCall?.name===Tn,zl=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(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.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},Fa=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ms(n))continue;let o=zl(n.toolCall?.args);return o.length>0?o:null}return null},Vp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var ql={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ss,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},Vl={name:Ts,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:ql,origin:"sdk",annotations:{readOnlyHint:!0}},Pr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Vl),Vp(e)&&t.push(Na),t};var Vn=require("partial-json"),_a=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)}},Sh=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Kp=e=>e.status==="complete"?Sh(e):e.status==="pending"?"Waiting":"",Th=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 Gp=e=>e.status==="complete"?Th(e):"Using tool...",$a=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ls=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 $a(t)},ja=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return $a(t)},Kl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",s=Ls(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,s)},Ua=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,r=0,a;for(;(a=s.exec(n))!==null;)a.index>r&&ks(o,n.slice(r,a.index),[]),a[1]!==void 0?ks(o,a[1],["bold"]):a[2]!==void 0?ks(o,a[2],["italic"]):a[3]!==void 0&&ks(o,a[3],["dim"]),r=a.index+a[0].length;return r<n.length&&ks(o,n.slice(r),[]),o},ks=(e,t,n)=>{let o=t.split("{duration}");for(let s=0;s<o.length;s++)o[s]&&e.push({text:o[s],styles:n}),s<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Eh=()=>{let e=null,t=0,n=o=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,r=o.match(s);if(r&&r[1])try{return r[1].replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[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 s=o.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let r=n(o);return r!==null&&(e=r),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ps=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},za=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},qa=()=>{let e=Eh();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)}},Va=()=>{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 s=(0,Vn.parse)(n,Vn.STR|Vn.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?_a(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=_a(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Jp=e=>{let t=null,n=0,s=e||(r=>{if(!r||typeof r!="object")return null;let a=i=>typeof i=="string"?_a(i):null;if(r.component&&typeof r.component=="string")return typeof r.text=="string"?_a(r.text):"";if(r.type==="init"&&r.form)return"";if(r.action)switch(r.action){case"nav_then_click":return a(r.on_load_text)||a(r.text)||null;case"message":case"message_and_click":case"checkout":return a(r.text)||null;default:return a(r.text)||a(r.display_text)||a(r.message)||null}return a(r.text)||a(r.display_text)||a(r.message)||a(r.content)||null});return{getExtractedText:()=>t,processChunk:r=>{let a=r.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let i=(0,Vn.parse)(r,Vn.STR|Vn.OBJ),p=s(i);p!==null&&(t=p)}catch{}return n=r.length,{text:t||"",raw:r}},close:()=>{}}},Ka=()=>{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 Xp="4.9.0";var hn=Xp;var kh="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function Lh(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 s=t.indexOf("/");if(s>0){let r=t.slice(s+1).split(";")[0]?.trim()??"";if(r&&r!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(r))return`attachment.${r}`}return"attachment"}var Gl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Ph(e){switch(e){case"json":return Va;case"regex-json":return qa;case"xml":return Ka;default:return za}}var Qp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Rh(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 s=Qp(n);if(!Qp(o))return e;if(!s||o===n||o.startsWith(n))return t;let a=Ps(e);return Ps(t)!==null&&a===null?t:e}var Yo=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??kh,this.headers={"Content-Type":"application/json","X-Persona-Version":hn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Ph(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 Er(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:s}=this.config;if(!o)return{agentId:t,flowId:n};let r=Rp(o,s);return r.kind==="agentId"?{agentId:r.agentId}:r.kind==="flowId"?{flowId:r.flowId}:{targetPayload:r.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ga}/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,s={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hn},body:JSON.stringify(s)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await r.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$/,"")||Ga}/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 s={...t,...this.config.clientToken&&{token:this.config.clientToken}},r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hn},body:JSON.stringify(s)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.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 s=await this.buildPayload(t.messages),r=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Gl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...r&&Object.keys(r).length>0&&{metadata:r},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,s.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":hn},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 s=o instanceof Error?o:new Error(String(o));throw!s.message.includes("Session expired")&&!s.message.includes("Message limit")&&n({type:"error",error:s}),s}}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 s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,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 r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Chat backend request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.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 s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,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 r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Agent execution request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let s=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ga}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(s,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,s){let r=!!(n&&n.length>0),a=r?Lp(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=r&&i&&this.lastSentClientToolsFingerprint===a,d=!r&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let y=0;;y++){if(u=await o({...r&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&y===0&&r&&(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,r?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let s=this.isClientTokenMode(),r=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ga}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),s&&a){let d=[...Pr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,y=>{let f={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(r,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(r,{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 s=>{try{let r=await s({messages:t,config:this.config});r&&typeof r=="object"&&Object.assign(n,r)}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",r)}}));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(Gl).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})),s={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...Pr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];r.length>0&&(s.clientTools=r);let a=await this.buildContextAggregate(t);return a&&(s.context=a),s}async buildPayload(t){let n=t.slice().filter(Gl).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(),s={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"&&(s[i]=p);let r=[...Pr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];r.length>0&&(s.clientTools=r);let a=await this.buildContextAggregate(t);if(a&&(s.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...s},config:this.config});if(i&&typeof i=="object"){let p=i;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return s}async handleCustomSSEEvent(t,n,o,s,r,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:r(),...c!==void 0&&{partId:c}};return o.current=u,s(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,s(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,s(c)}return i.done&&(o.current&&(o.current.streaming=!1,s(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,s){let r=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=k=>{let X=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,x=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,E=k.tools?k.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...k,reasoning:X,toolCall:x,tools:E}},y=k=>{if(k.role!=="assistant"||k.variant)return!0;let X=Array.isArray(k.contentParts)&&k.contentParts.length>0,x=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||X||x||!!k.stopReason},f=k=>{y(k)&&n({type:"message",message:u(k)})},h=null,C=null,M={current:null},P={current:null},I=null,A="",W=new Map,$=new Map,N=new Map,w=new Map,z=new Map,V={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},O=k=>{if(k==null)return null;try{return String(k)}catch{return null}},U=k=>O(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),me=k=>O(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),be=o,Me=!1,Oe=()=>{if(h)return h;let k,X="",x=I;return!Me&&be?(k=be,Me=!0,X=s??""):be&&x?k=`${be}_${x}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:k,role:"assistant",content:X,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},ae=(k,X)=>{V.lastId=X,k&&V.byStep.set(k,X)},ve=(k,X)=>{let x=k.reasoningId??k.id,E=U(k);if(x){let B=String(x);return ae(E,B),B}if(E){let B=V.byStep.get(E);if(B)return V.lastId=B,B}if(V.lastId&&!X)return V.lastId;if(!X)return null;let L=`reason-${c()}`;return ae(E,L),L},Z=k=>{let X=w.get(k);if(X)return X;let x={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:k,status:"streaming",chunks:[]}};return w.set(k,x),f(x),x},de=(k,X)=>{Y.lastId=X,k&&Y.byCall.set(k,X)},ee=new Set,Ce=new Map,he=new Set,fe=new Map,Re=k=>{if(!k)return!1;let X=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return X==="emit_artifact_markdown"||X==="emit_artifact_component"},Ne=(k,X)=>{let x=k.toolId??k.id,E=me(k);if(x){let B=String(x);return de(E,B),B}if(E){let B=Y.byCall.get(E);if(B)return Y.lastId=B,B}if(Y.lastId&&!X)return Y.lastId;if(!X)return null;let L=`tool-${c()}`;return de(E,L),L},ze=k=>{let X=z.get(k);if(X)return X;let x={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:k,status:"pending"}};return z.set(k,x),f(x),x},Fe=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let X=Number(k);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let x=Date.parse(k);if(!Number.isNaN(x))return x}return Date.now()},Ae=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Pe=new Map,rt=new Map,le=new Map,Ie=(k,X,x)=>{let E=le.get(k);E||(E=[],le.set(k,E));let L=0,B=E.length;for(;L<B;){let D=L+B>>>1;E[D].seq<X?L=D+1:B=D}E[L]?.seq===X?E[L]={seq:X,text:x}:E.splice(L,0,{seq:X,text:x});let J="";for(let D=0;D<E.length;D++)J+=E[D].text;return J},Ct=(k,X)=>{let x=Ae(X),E=rt.get(k.id),L=Rh(E,x);k.rawContent=L;let B=Pe.get(k.id),J=Ee=>{let dt=k.content??"";Ee.trim()!==""&&(dt.trim().length===0||Ee.startsWith(dt)||Ee.trimStart().startsWith(dt.trim()))&&(k.content=Ee)},D=()=>{if(B){let Ee=B.close?.();Ee instanceof Promise&&Ee.catch(()=>{})}Pe.delete(k.id),rt.delete(k.id),k.streaming=!1,f(k)};if(!B){J(x),D();return}let q=Ps(L);if(q!==null&&q.trim()!==""){J(q),D();return}let ie=Ee=>{let dt=typeof Ee=="string"?Ee:Ee?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let K=B.getExtractedText();return K!==null&&K.trim()!==""?K:x},nt;try{nt=B.processChunk(L)}catch{J(x),D();return}if(nt instanceof Promise){nt.then(Ee=>{J(ie(Ee)),D()}).catch(()=>{J(x),D()});return}J(ie(nt)),D()},bt=null,st=(k,X,x,E)=>{k.rawContent=X,Pe.has(k.id)||Pe.set(k.id,this.createStreamParser());let L=Pe.get(k.id),B=X.trim().startsWith("{")||X.trim().startsWith("[");if(B&&rt.set(k.id,X),L.__isPlainTextParser===!0){k.content=E!==void 0?X:k.content+x,rt.delete(k.id),Pe.delete(k.id),k.rawContent=void 0,f(k);return}let D=L.processChunk(X);if(D instanceof Promise)D.then(q=>{let ie=typeof q=="string"?q:q?.text??null;ie!==null&&ie.trim()!==""?(k.content=ie,f(k)):!B&&!X.trim().startsWith("<")&&(k.content=E!==void 0?X:k.content+x,rt.delete(k.id),Pe.delete(k.id),k.rawContent=void 0,f(k))}).catch(()=>{k.content=E!==void 0?X:k.content+x,rt.delete(k.id),Pe.delete(k.id),k.rawContent=void 0,f(k)});else{let q=typeof D=="string"?D:D?.text??null;q!==null&&q.trim()!==""?(k.content=q,f(k)):!B&&!X.trim().startsWith("<")&&(k.content=E!==void 0?X:k.content+x,rt.delete(k.id),Pe.delete(k.id),k.rawContent=void 0,f(k))}},ke=(k,X)=>{let x=X??k.content;if(x==null||x===""){k.streaming=!1,f(k);return}let L=rt.get(k.id)??Ae(x);k.rawContent=L;let B=Pe.get(k.id),J=null,D=!1;if(B&&(J=B.getExtractedText(),J===null&&(J=Ps(L)),J===null)){let q=B.processChunk(L);q instanceof Promise?(D=!0,q.then(ie=>{let nt=typeof ie=="string"?ie:ie?.text??null;nt!==null&&(k.content=nt,k.streaming=!1,Pe.delete(k.id),rt.delete(k.id),f(k))}).catch(()=>{})):J=typeof q=="string"?q:q?.text??null}if(!D){J!==null&&J.trim()!==""?k.content=J:rt.has(k.id)||(k.content=Ae(x));let q=Pe.get(k.id);if(q){let ie=q.close?.();ie instanceof Promise&&ie.catch(()=>{}),Pe.delete(k.id)}rt.delete(k.id),k.streaming=!1,f(k)}},ye=(k,X,x)=>{let E=$.get(k);if(E)return E;let L={id:`nested-${X}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:X}};return $.set(k,L),f(L),L},ct=[],We,ge=new Map,ce=0,xe="agent",wt=!1,F=null,ne=null,_e=new Map,Te=this.config.iterationDisplay??"separate";for(We=()=>{for(let k=0;k<ct.length;k++){let X=ct[k].payloadType,x=ct[k].payload;if(!wt&&xe!=="flow"&&typeof x.stepType=="string"&&(xe="flow"),X==="reasoning_start"){let E=typeof x.id=="string"?x.id:null,L=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(E&&L){W.set(E,L),ye(E,L,"reasoning");continue}let B=ve(x,!0)??`reason-${c()}`,J=Z(B);J.reasoning=J.reasoning??{id:B,status:"streaming",chunks:[]},J.reasoning.startedAt=J.reasoning.startedAt??Fe(x.startedAt??x.timestamp),J.reasoning.completedAt=void 0,J.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(J.reasoning.scope=x.scope),J.streaming=!0,J.reasoning.status="streaming",f(J)}else if(X==="reasoning_delta"){let E=typeof x.id=="string"?x.id:null;if(E&&W.has(E)&&$.has(E)){let D=$.get(E),q=x.reasoningText??x.text??x.delta??"";q&&x.hidden!==!0&&D.reasoning&&(D.reasoning.chunks.push(String(q)),f(D));continue}let L=ve(x,!1)??ve(x,!0)??`reason-${c()}`,B=Z(L);B.reasoning=B.reasoning??{id:L,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Fe(x.startedAt??x.timestamp);let J=x.reasoningText??x.text??x.delta??"";if(J&&x.hidden!==!0){let D=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(D!==void 0){let q=Ie(L,D,String(J));B.reasoning.chunks=[q]}else B.reasoning.chunks.push(String(J))}if(B.reasoning.status=x.done?"complete":"streaming",x.done){B.reasoning.completedAt=Fe(x.completedAt??x.timestamp);let D=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-D)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(X==="reasoning_complete"){let E=typeof x.id=="string"?x.id:null;if(E&&W.has(E)&&$.has(E)){let q=$.get(E);if(q.reasoning){let ie=typeof x.text=="string"?x.text:"";ie&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(ie),q.reasoning.status="complete",q.streaming=!1,f(q)}W.delete(E),$.delete(E);continue}let L=ve(x,!1)??ve(x,!0)??`reason-${c()}`,B=typeof x.text=="string"?x.text:"";!w.get(L)&&(B||x.scope==="loop")&&Z(L);let J=w.get(L);if(J?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(J.reasoning.scope=x.scope),B&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(B),J.reasoning.status="complete",J.reasoning.completedAt=Fe(x.completedAt??x.timestamp);let q=J.reasoning.startedAt??Date.now();J.reasoning.durationMs=Math.max(0,(J.reasoning.completedAt??Date.now())-q),J.streaming=!1,f(J)}let D=U(x);D&&V.byStep.delete(D)}else if(X==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof x.iteration=="number"&&(ce=x.iteration);let E=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??Ne(x,!0)??`tool-${c()}`,L=x.toolName??x.name;if(Re(L)){ee.add(E);continue}de(me(x),E);let B=ze(E),J=B.toolCall??{id:E,status:"pending"};J.name=L??J.name,J.status="running",x.parameters!==void 0?J.args=x.parameters:x.args!==void 0&&(J.args=x.args),J.startedAt=J.startedAt??Fe(x.startedAt??x.timestamp),J.completedAt=void 0,J.durationMs=void 0,B.toolCall=J,B.streaming=!0,x.executionId&&(B.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(B)}else if(X==="tool_output_delta"){let E=Ne(x,!1)??Ne(x,!0)??`tool-${c()}`;if(ee.has(E))continue;let L=ze(E),B=L.toolCall??{id:E,status:"running"};B.startedAt=B.startedAt??Fe(x.startedAt??x.timestamp);let J=x.text??x.delta??x.message??"";J&&(B.chunks=B.chunks??[],B.chunks.push(String(J))),B.status="running",L.toolCall=B,L.streaming=!0;let D=x.agentContext;(D||x.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:D?.executionId??x.executionId,iteration:D?.iteration??x.iteration}),f(L)}else if(X==="tool_complete"){let E=Ne(x,!1)??Ne(x,!0)??`tool-${c()}`;if(ee.has(E)){ee.delete(E);continue}let L=ze(E),B=L.toolCall??{id:E,status:"running"};B.status="complete",x.result!==void 0&&(B.result=x.result),typeof x.duration=="number"&&(B.duration=x.duration),B.completedAt=Fe(x.completedAt??x.timestamp);let J=x.duration??x.executionTime;if(typeof J=="number")B.durationMs=J;else{let ie=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-ie)}L.toolCall=B,L.streaming=!1;let D=x.agentContext;(D||x.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:D?.executionId??x.executionId,iteration:D?.iteration??x.iteration}),f(L);let q=me(x);q&&Y.byCall.delete(q)}else if(X==="await"&&x.toolName){let E=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,L=E??x.toolId??`local-${c()}`,B=ze(L),J=x.toolName,D=x.origin==="webmcp"&&!po(J)?`webmcp:${J}`:J,q=po(D),ie=B.toolCall??{id:L,status:"pending"};ie.name=D,ie.args=x.parameters,ie.status=q?"running":"complete",ie.chunks=ie.chunks??[],ie.startedAt=ie.startedAt??Fe(x.startedAt??x.timestamp??x.awaitedAt),q?(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:x.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...E?{webMcpToolCallId:E}:{}},f(B)}else if(X==="text_start"){let E=typeof x.id=="string"?x.id:null,L=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(E&&L){W.set(E,L);continue}let B=h;B&&(xe==="flow"?(ke(B),bt=B):(B.streaming=!1,f(B)),h=null),I=typeof x.id=="string"?x.id:I,A=""}else if(X==="text_delta"){let E=typeof x.id=="string"?x.id:null,L=E?W.get(E):void 0;if(E&&L){let J=typeof x.delta=="string"?x.delta:"",D=(N.get(E)??"")+J;if(N.set(E,D),D.trim()==="")continue;let q=ye(E,L);q.agentMetadata={...q.agentMetadata,executionId:x.executionId,parentToolId:L},st(q,D,J,void 0);continue}if(I=typeof x.id=="string"?x.id:I,xe==="flow"){let J=typeof x.delta=="string"?x.delta:"";if(A+=J,A.trim()==="")continue;let D=Oe();D.agentMetadata={executionId:x.executionId,iteration:x.iteration},st(D,A,J,void 0),C=D;continue}let B=Oe();B.content+=x.delta??"",B.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:F??void 0,agentName:ne?.agentName},C=B,f(B)}else if(X==="text_complete"){let E=typeof x.id=="string"?x.id:null;if(E&&W.has(E)){let B=$.get(E);B&&ke(B),W.delete(E),N.delete(E),$.delete(E);continue}let L=h;L&&(xe==="flow"?(ke(L),bt=L):((L.content??"")===""&&typeof x.text=="string"&&(L.content=x.text),L.streaming=!1,f(L)),h=null),I=null,A=""}else if(X==="step_complete"){let E=x.stepType,L=x.executionType;if(E==="tool"||L==="context")continue;if(x.success===!1){let B=x.error,J=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(J)});let D=h;D&&D.streaming&&(D.streaming=!1,f(D)),n({type:"status",status:"idle"});continue}{let B=bt;bt=null;let J=x.stopReason,D=x.result?.response;if(B)J&&(B.stopReason=J),D!=null?Ct(B,D):B.streaming!==!1&&(Pe.delete(B.id),rt.delete(B.id),B.streaming=!1,f(B));else{let q=D!=null&&D!=="";if(q||J){let ie=Oe();J&&(ie.stopReason=J),q?ke(ie,D):(ie.streaming=!1,f(ie))}}continue}}else if(X==="execution_start")xe=x.kind==="flow"?"flow":"agent",wt=!0,xe==="agent"&&(ne={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:Fe(x.startedAt)});else if(X==="turn_start"){let E=typeof x.iteration=="number"?x.iteration:ce;if(E!==ce){if(ne&&(ne.currentIteration=E),Te==="separate"&&E>1){let L=h;L&&(L.streaming=!1,f(L),_e.set(E-1,L),h=null)}ce=E}F=typeof x.id=="string"?x.id:null,C=null}else if(X==="tool_input_delta"){let E=x.toolCallId??Y.lastId;if(E){let L=z.get(E);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(x.delta??""),f(L))}}else{if(X==="tool_input_complete")continue;if(X==="turn_complete"){let E=x.stopReason,L=h??C;if(E&&L!==null){let B=x.id;(!B||L.agentMetadata?.turnId===B)&&(L.stopReason=E,f(L))}F===x.id&&(F=null)}else if(X==="media_start"){let E=String(x.id);ge.set(E,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(X==="media_delta"){let E=ge.get(String(x.id));E&&typeof x.delta=="string"&&E.parts.push(x.delta)}else if(X==="media_complete"){let E=String(x.id),L=ge.get(E);ge.delete(E);let B=(typeof x.mediaType=="string"?x.mediaType:void 0)??L?.mediaType??"application/octet-stream",J=typeof x.data=="string"?x.data:void 0,D=typeof x.url=="string"?x.url:L&&L.parts.length>0?L.parts.join(""):void 0,q=null;if(J)q={type:"media",data:J,mediaType:B};else if(D){let dt=B.toLowerCase();q={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:D,mediaType:B}}let ie=x.toolCallId??L?.toolCallId,nt=q?[q]:[],Ee=[];for(let dt of nt){if(!dt||typeof dt!="object")continue;let K=dt,qe=typeof K.type=="string"?K.type:void 0,He=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Be=null,Le="";if(qe==="media"){let Ye=typeof K.data=="string"?K.data:void 0;if(!Ye)continue;Le=He.length>0?He:"application/octet-stream",Be=`data:${Le};base64,${Ye}`}else if(qe==="image-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;Le=He,Be=Ye}else if(qe==="file-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;Le=He,Be=Ye}else continue;if(Be)if(qe==="image-url"||Le.startsWith("image/"))Ee.push({type:"image",image:Be,...Le.includes("/")?{mimeType:Le}:{}});else if(Le.startsWith("audio/"))Ee.push({type:"audio",audio:Be,mimeType:Le});else if(Le.startsWith("video/"))Ee.push({type:"video",video:Be,mimeType:Le});else{let Ye=Le||"application/octet-stream";Ee.push({type:"file",data:Be,mimeType:Ye,filename:Lh(Ye)})}}if(Ee.length>0){let dt=c(),K=ie,He={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:Ee,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ce}};f(He);let Be=h;Be&&(Be.streaming=!1,f(Be)),h=null,M.current=null}}else if(X==="execution_complete"){let E=x.kind??xe;E==="agent"&&ne&&(ne.status=x.success?"complete":"error",ne.completedAt=Fe(x.completedAt),ne.stopReason=x.stopReason);let L=h;L&&(E==="flow"&&L.streaming!==!1?ke(L):(L.streaming=!1,f(L)),h=null),I=null,A="",bt=null,n({type:"status",status:"idle",terminal:!0})}else if(X==="execution_error"){let E=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(E)})}else if(X!=="ping"){if(X==="approval_start"){let E=x.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:ne?.agentId??"virtual",executionId:x.executionId??ne?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(L)}else if(X==="step_await"&&x.awaitReason==="approval_required"){let E=x.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:ne?.agentId??"virtual",executionId:x.executionId??ne?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(L)}else if(X==="approval_complete"){let E=x.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:x.decision??"approved",agentId:ne?.agentId??"virtual",executionId:x.executionId??ne?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(B)}}else if(X==="artifact_start"||X==="artifact_delta"||X==="artifact_update"||X==="artifact_complete"){if(X==="artifact_start"){let E=x.artifactType,L=String(x.id),B=typeof x.title=="string"?x.title:void 0,J=x.file,D;J&&typeof J=="object"&&!Array.isArray(J)&&typeof J.path=="string"&&typeof J.mimeType=="string"&&(D={path:J.path,mimeType:J.mimeType,...typeof J.language=="string"?{language:J.language}:{}}),n({type:"artifact_start",id:L,artifactType:E,title:B,component:typeof x.component=="string"?x.component:void 0,...D?{file:D}:{}});let q=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(fe.set(L,{markdown:"",title:B,file:D,...q?{props:q}:{}}),!he.has(L)){he.add(L);let ie=Xo(this.config.features?.artifacts,E),nt=typeof x.component=="string"?x.component:void 0,Ee={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ha(ie,{artifactId:L,title:B,artifactType:E,status:"streaming",...D?{file:D}:{},...nt?{component:nt}:{}})};Ce.set(L,Ee),f(Ee)}}else if(X==="artifact_delta"){let E=String(x.id),L=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:E,artDelta:L});let B=fe.get(E);B&&(B.markdown+=L)}else if(X==="artifact_update"){let E=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:E,component:typeof x.component=="string"?x.component:void 0});let L=fe.get(String(x.id));L&&(L.props={...L.props??{},...E})}else if(X==="artifact_complete"){let E=String(x.id);n({type:"artifact_complete",id:E});let L=Ce.get(E);if(L){L.streaming=!1;try{let B=JSON.parse(L.rawContent??"{}");if(B.props){B.props.status="complete";let J=fe.get(E);J?.markdown&&(B.props.markdown=J.markdown),J?.file&&(B.props.file=J.file),B.component==="PersonaArtifactInline"&&J?.props&&Object.keys(J.props).length>0&&(B.props.componentProps=J.props)}L.rawContent=JSON.stringify(B)}catch{}fe.delete(E),f(L),Ce.delete(E)}}}else if(X==="transcript_insert"){let E=x.message;if(!E||typeof E!="object")continue;let L=String(E.id??`msg-${c()}`),B=E.role,D={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(f(D),D.rawContent)try{let ie=JSON.parse(D.rawContent)?.props?.artifactId;typeof ie=="string"&&he.add(ie)}catch{}h=null,M.current=null,Pe.delete(L),rt.delete(L)}else if(X==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let E=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(E)});let L=h;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}else if(X==="step_error"||X==="dispatch_error"||X==="flow_error"){let E=null;if(x.error instanceof Error)E=x.error;else if(X==="dispatch_error"){let L=x.message??x.error;L!=null&&L!==""&&(E=new Error(String(L)))}else{let L=x.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=h;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}ct.length=0};;){let{done:k,value:X}=await r.read();if(k)break;i+=a.decode(X,{stream:!0});let x=i.split(`
8
+ ${e.description}`:"");return window.confirm(n)},th=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)}},nh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},oh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Xo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ba(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 rh="agent_",sh="flow_";function Rp(e){return e.startsWith(rh)?{kind:"agentId",agentId:e}:e.startsWith(sh)?{kind:"flowId",flowId:e}:null}function Ip(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=Rp(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=Rp(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},In=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Wp=()=>document.createDocumentFragment(),Fe=(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},Un=(...e)=>e.filter(Boolean).join(" ");var Ts="ask_user_question",Ss=8,Mr="data-persona-ask-sheet-for",ah="Other",ih="Other\u2026",Bp="Type your own answer here",Dp="Send",lh="Next",ch="Back",dh="Submit all",ph="Skip",uh=3,Nl="data-ask-current-index",Fl="data-ask-question-count",Op="data-ask-answers",_l="data-ask-grouped",Np="data-ask-layout",fh=e=>e.layout==="pills"?"pills":"rows",gh=e=>e.getAttribute(Np)==="pills"?"pills":"rows",Hp=!1,Fp=e=>e.replace(/["\\]/g,"\\$&"),zn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ts,Da=e=>e?.features?.askUserQuestion??{},qn=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}},Es=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ss&&!Hp&&(Hp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ss}.`)),t.slice(0,Ss)},mh=e=>Es(e)[0]??null,hh=(e,t)=>Es(e)[t]??null,_p=(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))},$p=(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},yh=(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=$p(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},bh=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},vh=(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<uh;c++)s.appendChild(bh(o));return s}if(p.forEach((c,u)=>{s.appendChild(yh(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?ah:ih;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 y=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Bp,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),y.appendChild(f),u.appendChild(y);let h=$p(o,a,p.length);h&&u.appendChild(h),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},jp=(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??Bp,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??Dp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},xh=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??Dp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ch=(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??ph,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??dh:n.nextLabel??lh,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Qo=e=>{let t=e.getAttribute(Op);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Up=(e,t)=>{e.setAttribute(Op,JSON.stringify(t))},gn=e=>{let t=Number(e.getAttribute(Nl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wh=(e,t)=>{e.setAttribute(Nl,String(Math.max(0,Math.floor(t))))},kr=e=>{let t=Number(e.getAttribute(Fl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},fo=e=>e.getAttribute(_l)==="true",Ah=(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},Sh=(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)))},Oa=(e,t)=>{let{payload:n}=qn(t),o=Es(n),r=Qo(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},zp=e=>{let t=Qo(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="")},qp=e=>{if(!fo(e))return;let t=Qo(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}},$l=(e,t,n)=>{let o=Da(n),r=gh(e),{payload:s,complete:a}=qn(t),i=fo(e),p=gn(e),d=kr(e),c=i?hh(s,p):mh(s),u=!!c?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let I=typeof c?.question=="string"?c.question:"";h.textContent=I,h.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let I=vh(c,o,a,r);C.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(jp(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(xh(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=Ch(p,d,o);P?P.replaceWith(I):e.appendChild(I)}else P&&P.remove();zp(e),qp(e)},Th=(e,t,n)=>{let o=Da(t),r=fh(o),s=e.toolCall.id,a=Es(n),i=Math.max(1,a.length),p=i>1,d=Ah(e,a),c=p?Sh(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Mr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Fl,String(i)),u.setAttribute(Nl,String(c)),u.setAttribute(_l,p?"true":"false"),u.setAttribute(Np,r),Up(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`),_p(u,o);let y=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",y.appendChild(f);let h=m("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",y.appendChild(h),u.appendChild(y);let M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),r!=="rows"&&u.appendChild(jp(o,r)),$l(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Eh=(e,t,n)=>{let{payload:o}=qn(t),r=Math.max(1,Es(o).length);r>kr(e)&&(e.setAttribute(Fl,String(r)),r>1&&!fo(e)&&e.setAttribute(_l,"true")),$l(e,t,n)},Vp=(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=Da(t);_p(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=qn(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Lr=(e,t,n)=>{if(!n||!zn(e)||Da(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Mr}]`).forEach(d=>{d.getAttribute(Mr)!==r&&d.remove()});let a=n.querySelector(`[${Mr}="${Fp(r)}"]`);if(a){Eh(a,e,t);return}let{payload:i}=qn(e),p=Th(e,t,i);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${Mr}="${Fp(t)}"]`:`[${Mr}]`;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)})},jl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),mo=(e,t)=>{let n=Qo(e),o=gn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Up(e,n),zp(e),qp(e)},Na=(e,t,n,o)=>{let r=kr(e),s=Math.max(0,Math.min(r-1,o));wh(e,s),$l(e,t,n)};var Tn="suggest_replies";var Ul={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Fa={name:Tn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Ul,origin:"sdk",annotations:{readOnlyHint:!0}},zl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ms=e=>e.variant==="tool"&&e.toolCall?.name===Tn,ql=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},_a=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ms(n))continue;let o=ql(n.toolCall?.args);return o.length>0?o:null}return null},Kp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Vl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ss,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},Kl={name:Ts,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:Vl,origin:"sdk",annotations:{readOnlyHint:!0}},Pr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Kl),Kp(e)&&t.push(Fa),t};var Vn=require("partial-json"),$a=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)}},Mh=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`},Gp=e=>e.status==="complete"?Mh(e):e.status==="pending"?"Waiting":"",kh=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 Jp=e=>e.status==="complete"?kh(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ls=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 ja(t)},Ua=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ja(t)},Gl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ls(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},za=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ks(o,n.slice(s,a.index),[]),a[1]!==void 0?ks(o,a[1],["bold"]):a[2]!==void 0?ks(o,a[2],["italic"]):a[3]!==void 0&&ks(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ks(o,n.slice(s),[]),o},ks=(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})},Lh=()=>{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
+ `).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()=>{}}},Ps=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},qa=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Va=()=>{let e=Lh();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)}},Ka=()=>{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,Vn.parse)(n,Vn.STR|Vn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?$a(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=$a(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Xp=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(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,Vn.parse)(s,Vn.STR|Vn.OBJ),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Ga=()=>{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 Qp="4.10.0";var mn=Qp;var Rh="https://api.runtype.com/v1/dispatch",Ja="https://api.runtype.com";function Ih(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 Jl=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 Wh(e){switch(e){case"json":return Ka;case"regex-json":return Va;case"xml":return Ga;default:return qa}}var Yp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Hh(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=Yp(n);if(!Yp(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ps(e);return Ps(t)!==null&&a===null?t:e}var Yo=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??Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":mn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Wh(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 Er(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=Ip(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$/,"")||Ja}/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":mn},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$/,"")||Ja}/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":mn},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(Jl).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":mn},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$/,"")||Ja}/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?Pp(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 y=0;;y++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&y===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(/\/+$/,"")||Ja}/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=[...Pr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,y=>{let f={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),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(Jl).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=[...Pr(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(Jl).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=[...Pr(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=k=>{let F=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,v=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,S=k.tools?k.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...k,reasoning:F,toolCall:v,tools:S}},y=k=>{if(k.role!=="assistant"||k.variant)return!0;let F=Array.isArray(k.contentParts)&&k.contentParts.length>0,v=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||F||v||!!k.stopReason},f=k=>{y(k)&&n({type:"message",message:u(k)})},h=null,C=null,M={current:null},P={current:null},I=null,A="",W=new Map,$=new Map,N=new Map,w=new Map,q=new Map,V={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},O=k=>{if(k==null)return null;try{return String(k)}catch{return null}},U=k=>O(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),me=k=>O(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),ve=o,Me=!1,Oe=()=>{if(h)return h;let k,F="",v=I;return!Me&&ve?(k=ve,Me=!0,F=r??""):ve&&v?k=`${ve}_${v}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:k,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},ie=(k,F)=>{V.lastId=F,k&&V.byStep.set(k,F)},xe=(k,F)=>{let v=k.reasoningId??k.id,S=U(k);if(v){let B=String(v);return ie(S,B),B}if(S){let B=V.byStep.get(S);if(B)return V.lastId=B,B}if(V.lastId&&!F)return V.lastId;if(!F)return null;let L=`reason-${c()}`;return ie(S,L),L},Z=k=>{let F=w.get(k);if(F)return F;let v={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:k,status:"streaming",chunks:[]}};return w.set(k,v),f(v),v},ce=(k,F)=>{Y.lastId=F,k&&Y.byCall.set(k,F)},ee=new Set,we=new Map,he=new Set,ue=new Map,Re=k=>{if(!k)return!1;let F=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return F==="emit_artifact_markdown"||F==="emit_artifact_component"},Ne=(k,F)=>{let v=k.toolId??k.id,S=me(k);if(v){let B=String(v);return ce(S,B),B}if(S){let B=Y.byCall.get(S);if(B)return Y.lastId=B,B}if(Y.lastId&&!F)return Y.lastId;if(!F)return null;let L=`tool-${c()}`;return ce(S,L),L},je=k=>{let F=q.get(k);if(F)return F;let v={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:k,status:"pending"}};return q.set(k,v),f(v),v},Be=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let F=Number(k);if(!Number.isNaN(F)&&Number.isFinite(F))return F;let v=Date.parse(k);if(!Number.isNaN(v))return v}return Date.now()},Ue=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Xe=new Map,ke=new Map,oe=new Map,Ie=(k,F,v)=>{let S=oe.get(k);S||(S=[],oe.set(k,S));let L=0,B=S.length;for(;L<B;){let D=L+B>>>1;S[D].seq<F?L=D+1:B=D}S[L]?.seq===F?S[L]={seq:F,text:v}:S.splice(L,0,{seq:F,text:v});let K="";for(let D=0;D<S.length;D++)K+=S[D].text;return K},Ct=(k,F)=>{let v=Ue(F),S=ke.get(k.id),L=Hh(S,v);k.rawContent=L;let B=Xe.get(k.id),K=Te=>{let ct=k.content??"";Te.trim()!==""&&(ct.trim().length===0||Te.startsWith(ct)||Te.trimStart().startsWith(ct.trim()))&&(k.content=Te)},D=()=>{if(B){let Te=B.close?.();Te instanceof Promise&&Te.catch(()=>{})}Xe.delete(k.id),ke.delete(k.id),k.streaming=!1,f(k)};if(!B){K(v),D();return}let z=Ps(L);if(z!==null&&z.trim()!==""){K(z),D();return}let re=Te=>{let ct=typeof Te=="string"?Te:Te?.text??null;if(ct!==null&&ct.trim()!=="")return ct;let G=B.getExtractedText();return G!==null&&G.trim()!==""?G:v},Qe;try{Qe=B.processChunk(L)}catch{K(v),D();return}if(Qe instanceof Promise){Qe.then(Te=>{K(re(Te)),D()}).catch(()=>{K(v),D()});return}K(re(Qe)),D()},yt=null,pt=(k,F,v,S)=>{k.rawContent=F,Xe.has(k.id)||Xe.set(k.id,this.createStreamParser());let L=Xe.get(k.id),B=F.trim().startsWith("{")||F.trim().startsWith("[");if(B&&ke.set(k.id,F),L.__isPlainTextParser===!0){k.content=S!==void 0?F:k.content+v,ke.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,f(k);return}let D=L.processChunk(F);if(D instanceof Promise)D.then(z=>{let re=typeof z=="string"?z:z?.text??null;re!==null&&re.trim()!==""?(k.content=re,f(k)):!B&&!F.trim().startsWith("<")&&(k.content=S!==void 0?F:k.content+v,ke.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,f(k))}).catch(()=>{k.content=S!==void 0?F:k.content+v,ke.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,f(k)});else{let z=typeof D=="string"?D:D?.text??null;z!==null&&z.trim()!==""?(k.content=z,f(k)):!B&&!F.trim().startsWith("<")&&(k.content=S!==void 0?F:k.content+v,ke.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,f(k))}},We=(k,F)=>{let v=F??k.content;if(v==null||v===""){k.streaming=!1,f(k);return}let L=ke.get(k.id)??Ue(v);k.rawContent=L;let B=Xe.get(k.id),K=null,D=!1;if(B&&(K=B.getExtractedText(),K===null&&(K=Ps(L)),K===null)){let z=B.processChunk(L);z instanceof Promise?(D=!0,z.then(re=>{let Qe=typeof re=="string"?re:re?.text??null;Qe!==null&&(k.content=Qe,k.streaming=!1,Xe.delete(k.id),ke.delete(k.id),f(k))}).catch(()=>{})):K=typeof z=="string"?z:z?.text??null}if(!D){K!==null&&K.trim()!==""?k.content=K:ke.has(k.id)||(k.content=Ue(v));let z=Xe.get(k.id);if(z){let re=z.close?.();re instanceof Promise&&re.catch(()=>{}),Xe.delete(k.id)}ke.delete(k.id),k.streaming=!1,f(k)}},ye=(k,F,v)=>{let S=$.get(k);if(S)return S;let L={id:`nested-${F}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:F}};return $.set(k,L),f(L),L},Ze=[],Le,ge=new Map,le=0,Ce="agent",wt=!1,be=null,fe=null,hn=new Map,Q=this.config.iterationDisplay??"separate";for(Le=()=>{for(let k=0;k<Ze.length;k++){let F=Ze[k].payloadType,v=Ze[k].payload;if(!wt&&Ce!=="flow"&&typeof v.stepType=="string"&&(Ce="flow"),F==="reasoning_start"){let S=typeof v.id=="string"?v.id:null,L=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&L){W.set(S,L),ye(S,L,"reasoning");continue}let B=xe(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",f(K)}else if(F==="reasoning_delta"){let S=typeof v.id=="string"?v.id:null;if(S&&W.has(S)&&$.has(S)){let D=$.get(S),z=v.reasoningText??v.text??v.delta??"";z&&v.hidden!==!0&&D.reasoning&&(D.reasoning.chunks.push(String(z)),f(D));continue}let L=xe(v,!1)??xe(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 D=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(D!==void 0){let z=Ie(L,D,String(K));B.reasoning.chunks=[z]}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 D=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-D)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(F==="reasoning_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&W.has(S)&&$.has(S)){let z=$.get(S);if(z.reasoning){let re=typeof v.text=="string"?v.text:"";re&&z.reasoning.chunks.length===0&&z.reasoning.chunks.push(re),z.reasoning.status="complete",z.streaming=!1,f(z)}W.delete(S),$.delete(S);continue}let L=xe(v,!1)??xe(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 z=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-z),K.streaming=!1,f(K)}let D=U(v);D&&V.byStep.delete(D)}else if(F==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof v.iteration=="number"&&(le=v.iteration);let S=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Ne(v,!0)??`tool-${c()}`,L=v.toolName??v.name;if(Re(L)){ee.add(S);continue}ce(me(v),S);let B=je(S),K=B.toolCall??{id:S,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}),f(B)}else if(F==="tool_output_delta"){let S=Ne(v,!1)??Ne(v,!0)??`tool-${c()}`;if(ee.has(S))continue;let L=je(S),B=L.toolCall??{id:S,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 D=v.agentContext;(D||v.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:D?.executionId??v.executionId,iteration:D?.iteration??v.iteration}),f(L)}else if(F==="tool_complete"){let S=Ne(v,!1)??Ne(v,!0)??`tool-${c()}`;if(ee.has(S)){ee.delete(S);continue}let L=je(S),B=L.toolCall??{id:S,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 re=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-re)}L.toolCall=B,L.streaming=!1;let D=v.agentContext;(D||v.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:D?.executionId??v.executionId,iteration:D?.iteration??v.iteration}),f(L);let z=me(v);z&&Y.byCall.delete(z)}else if(F==="await"&&v.toolName){let S=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,L=S??v.toolId??`local-${c()}`,B=je(L),K=v.toolName,D=v.origin==="webmcp"&&!po(K)?`webmcp:${K}`:K,z=po(D),re=B.toolCall??{id:L,status:"pending"};re.name=D,re.args=v.parameters,re.status=z?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Be(v.startedAt??v.timestamp??v.awaitedAt),z?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,B.toolCall=re,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:v.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},f(B)}else if(F==="text_start"){let S=typeof v.id=="string"?v.id:null,L=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&L){W.set(S,L);continue}let B=h;B&&(Ce==="flow"?(We(B),yt=B):(B.streaming=!1,f(B)),h=null),I=typeof v.id=="string"?v.id:I,A=""}else if(F==="text_delta"){let S=typeof v.id=="string"?v.id:null,L=S?W.get(S):void 0;if(S&&L){let K=typeof v.delta=="string"?v.delta:"",D=(N.get(S)??"")+K;if(N.set(S,D),D.trim()==="")continue;let z=ye(S,L);z.agentMetadata={...z.agentMetadata,executionId:v.executionId,parentToolId:L},pt(z,D,K,void 0);continue}if(I=typeof v.id=="string"?v.id:I,Ce==="flow"){let K=typeof v.delta=="string"?v.delta:"";if(A+=K,A.trim()==="")continue;let D=Oe();D.agentMetadata={executionId:v.executionId,iteration:v.iteration},pt(D,A,K,void 0),C=D;continue}let B=Oe();B.content+=v.delta??"",B.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:be??void 0,agentName:fe?.agentName},C=B,f(B)}else if(F==="text_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&W.has(S)){let B=$.get(S);B&&We(B),W.delete(S),N.delete(S),$.delete(S);continue}let L=h;L&&(Ce==="flow"?(We(L),yt=L):((L.content??"")===""&&typeof v.text=="string"&&(L.content=v.text),L.streaming=!1,f(L)),h=null),I=null,A=""}else if(F==="step_complete"){let S=v.stepType,L=v.executionType;if(S==="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 D=h;D&&D.streaming&&(D.streaming=!1,f(D)),n({type:"status",status:"idle"});continue}{let B=yt;yt=null;let K=v.stopReason,D=v.result?.response;if(B)K&&(B.stopReason=K),D!=null?Ct(B,D):B.streaming!==!1&&(Xe.delete(B.id),ke.delete(B.id),B.streaming=!1,f(B));else{let z=D!=null&&D!=="";if(z||K){let re=Oe();K&&(re.stopReason=K),z?We(re,D):(re.streaming=!1,f(re))}}continue}}else if(F==="execution_start")Ce=v.kind==="flow"?"flow":"agent",wt=!0,Ce==="agent"&&(fe={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Be(v.startedAt)});else if(F==="turn_start"){let S=typeof v.iteration=="number"?v.iteration:le;if(S!==le){if(fe&&(fe.currentIteration=S),Q==="separate"&&S>1){let L=h;L&&(L.streaming=!1,f(L),hn.set(S-1,L),h=null)}le=S}be=typeof v.id=="string"?v.id:null,C=null}else if(F==="tool_input_delta"){let S=v.toolCallId??Y.lastId;if(S){let L=q.get(S);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(v.delta??""),f(L))}}else{if(F==="tool_input_complete")continue;if(F==="turn_complete"){let S=v.stopReason,L=h??C;if(S&&L!==null){let B=v.id;(!B||L.agentMetadata?.turnId===B)&&(L.stopReason=S,f(L))}be===v.id&&(be=null)}else if(F==="media_start"){let S=String(v.id);ge.set(S,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(F==="media_delta"){let S=ge.get(String(v.id));S&&typeof v.delta=="string"&&S.parts.push(v.delta)}else if(F==="media_complete"){let S=String(v.id),L=ge.get(S);ge.delete(S);let B=(typeof v.mediaType=="string"?v.mediaType:void 0)??L?.mediaType??"application/octet-stream",K=typeof v.data=="string"?v.data:void 0,D=typeof v.url=="string"?v.url:L&&L.parts.length>0?L.parts.join(""):void 0,z=null;if(K)z={type:"media",data:K,mediaType:B};else if(D){let ct=B.toLowerCase();z={type:ct==="image"||ct.startsWith("image/")?"image-url":"file-url",url:D,mediaType:B}}let re=v.toolCallId??L?.toolCallId,Qe=z?[z]:[],Te=[];for(let ct of Qe){if(!ct||typeof ct!="object")continue;let G=ct,ze=typeof G.type=="string"?G.type:void 0,Ee=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",He=null,Pe="";if(ze==="media"){let tt=typeof G.data=="string"?G.data:void 0;if(!tt)continue;Pe=Ee.length>0?Ee:"application/octet-stream",He=`data:${Pe};base64,${tt}`}else if(ze==="image-url"){let tt=typeof G.url=="string"?G.url:void 0;if(!tt)continue;Pe=Ee,He=tt}else if(ze==="file-url"){let tt=typeof G.url=="string"?G.url:void 0;if(!tt)continue;Pe=Ee,He=tt}else continue;if(He)if(ze==="image-url"||Pe.startsWith("image/"))Te.push({type:"image",image:He,...Pe.includes("/")?{mimeType:Pe}:{}});else if(Pe.startsWith("audio/"))Te.push({type:"audio",audio:He,mimeType:Pe});else if(Pe.startsWith("video/"))Te.push({type:"video",video:He,mimeType:Pe});else{let tt=Pe||"application/octet-stream";Te.push({type:"file",data:He,mimeType:tt,filename:Ih(tt)})}}if(Te.length>0){let ct=c(),G=re,Ee={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${ct}`:String(ct)}`,role:"assistant",content:"",contentParts:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:ct,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:le}};f(Ee);let He=h;He&&(He.streaming=!1,f(He)),h=null,M.current=null}}else if(F==="execution_complete"){let S=v.kind??Ce;S==="agent"&&fe&&(fe.status=v.success?"complete":"error",fe.completedAt=Be(v.completedAt),fe.stopReason=v.stopReason);let L=h;L&&(S==="flow"&&L.streaming!==!1?We(L):(L.streaming=!1,f(L)),h=null),I=null,A="",yt=null,n({type:"status",status:"idle",terminal:!0})}else if(F==="execution_error"){let S=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(F!=="ping"){if(F==="approval_start"){let S=v.approvalId??`approval-${c()}`,L={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:fe?.agentId??"virtual",executionId:v.executionId??fe?.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}};f(L)}else if(F==="step_await"&&v.awaitReason==="approval_required"){let S=v.approvalId??`approval-${c()}`,L={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:fe?.agentId??"virtual",executionId:v.executionId??fe?.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}};f(L)}else if(F==="approval_complete"){let S=v.approvalId;if(S){let B={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:v.decision??"approved",agentId:fe?.agentId??"virtual",executionId:v.executionId??fe?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(B)}}else if(F==="artifact_start"||F==="artifact_delta"||F==="artifact_update"||F==="artifact_complete"){if(F==="artifact_start"){let S=v.artifactType,L=String(v.id),B=typeof v.title=="string"?v.title:void 0,K=v.file,D;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(D={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:L,artifactType:S,title:B,component:typeof v.component=="string"?v.component:void 0,...D?{file:D}:{}});let z=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(ue.set(L,{markdown:"",title:B,file:D,...z?{props:z}:{}}),!he.has(L)){he.add(L);let re=Xo(this.config.features?.artifacts,S),Qe=typeof v.component=="string"?v.component:void 0,Te={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ba(re,{artifactId:L,title:B,artifactType:S,status:"streaming",...D?{file:D}:{},...Qe?{component:Qe}:{}})};we.set(L,Te),f(Te)}}else if(F==="artifact_delta"){let S=String(v.id),L=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:S,artDelta:L});let B=ue.get(S);B&&(B.markdown+=L)}else if(F==="artifact_update"){let S=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:S,component:typeof v.component=="string"?v.component:void 0});let L=ue.get(String(v.id));L&&(L.props={...L.props??{},...S})}else if(F==="artifact_complete"){let S=String(v.id);n({type:"artifact_complete",id:S});let L=we.get(S);if(L){L.streaming=!1;try{let B=JSON.parse(L.rawContent??"{}");if(B.props){B.props.status="complete";let K=ue.get(S);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{}ue.delete(S),f(L),we.delete(S)}}}else if(F==="transcript_insert"){let S=v.message;if(!S||typeof S!="object")continue;let L=String(S.id??`msg-${c()}`),B=S.role,D={id:L,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:c()};if(f(D),D.rawContent)try{let re=JSON.parse(D.rawContent)?.props?.artifactId;typeof re=="string"&&he.add(re)}catch{}h=null,M.current=null,Xe.delete(L),ke.delete(L)}else if(F==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let S=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(S)});let L=h;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}else if(F==="step_error"||F==="dispatch_error"||F==="flow_error"){let S=null;if(v.error instanceof Error)S=v.error;else if(F==="dispatch_error"){let L=v.message??v.error;L!=null&&L!==""&&(S=new Error(String(L)))}else{let L=v.error;typeof L=="string"&&L!==""?S=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(S=new Error(String(L.message??L)))}if(S){n({type:"error",error:S});let L=h;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:k,value:F}=await s.read();if(k)break;i+=a.decode(F,{stream:!0});let v=i.split(`
12
12
 
13
- `);i=x.pop()??"";for(let E of x){let L=E.split(`
14
- `),B="message",J="",D=null;for(let Ee of L)Ee.startsWith("event:")?B=Ee.replace("event:","").trim():Ee.startsWith("data:")?J+=Ee.replace("data:","").trim():Ee.startsWith("id:")&&(D=Ee.slice(3).trim());let q=()=>{D!==null&&D!==""&&n({type:"cursor",id:D})};if(!J){q();continue}let ie;try{ie=JSON.parse(J)}catch(Ee){n({type:"error",error:Ee instanceof Error?Ee:new Error("Failed to parse chat stream payload")});continue}let nt=B!=="message"?B:ie.type??"message";if(this.onSSEEvent?.(nt,ie),this.parseSSEEvent){M.current=h;let Ee=await this.handleCustomSSEEvent(ie,n,M,f,c,P);if(M.current&&M.current!==h&&(h=M.current),Ee){q();continue}}ct.push({payloadType:nt,payload:ie}),We(),q()}}We()}};function Yp(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Rr(){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 Ja="[Image]";function Zp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function eu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Xa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function tu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function nu(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function ou(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function ru(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 su=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ih=["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"],Kn=[...su,...Ih];function Wh(e){return su.includes(e)||e.startsWith("image/")}function Qa(e){return Wh(e.type)}async function au(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Qa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function iu(e,t=Kn,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 Hh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function lu(e,t){let n=Hh(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"}Jl();var cu=16e3,Bh=24e3,Dh=4096,Oh=1380533830;function Nh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Oh?new Uint8Array(e,44):new Uint8Array(e)}function Fh(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 Rs=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 s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let r=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:cu,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){r.getTracks().forEach(u=>u.stop());return}this.mediaStream=r;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:cu});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ir(Bh);if(s!==this.callGeneration){p.destroy(),r.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Fh(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,r,c,s))},c.onmessage=u=>this.handleMessage(u,s),c.onerror=()=>{s===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(s===this.callGeneration){if(u.code!==1e3){let y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(r){throw this.cleanup(),this.emitError(r),this.emitStatus("error"),r}}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,s){let r=t.createMediaStreamSource(n);this.sourceNode=r;let a=t.createScriptProcessor(Dh,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==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)},r.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 s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,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=Nh(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(s=>s(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Zo=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(r=>r[0]).map(r=>r.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(r=>r({text:o,confidence:s?.8:.5,provider:"browser"})),s&&!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 Rs(e.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(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 Ya(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(Zo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Is(e){try{return Ya(e),!0}catch{return!1}}function Wr(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(s=>s.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 s=new SpeechSynthesisUtterance(t.text),r=o.getVoices();if(t.voice){let a=r.find(i=>i.name===t.voice);a&&(s.voice=a)}else r.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(r):Wr(r));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>n.onEnd?.(),s.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var er=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 s=await this.resolveEngine();if(o!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}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 Xl(e){if(!e)return"";let t=_h(e);return du(t!==null?t:e)}function _h(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 du(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);i=v.pop()??"";for(let S of v){let L=S.split(`
14
+ `),B="message",K="",D=null;for(let Te of L)Te.startsWith("event:")?B=Te.replace("event:","").trim():Te.startsWith("data:")?K+=Te.replace("data:","").trim():Te.startsWith("id:")&&(D=Te.slice(3).trim());let z=()=>{D!==null&&D!==""&&n({type:"cursor",id:D})};if(!K){z();continue}let re;try{re=JSON.parse(K)}catch(Te){n({type:"error",error:Te instanceof Error?Te:new Error("Failed to parse chat stream payload")});continue}let Qe=B!=="message"?B:re.type??"message";if(this.onSSEEvent?.(Qe,re),this.parseSSEEvent){M.current=h;let Te=await this.handleCustomSSEEvent(re,n,M,f,c,P);if(M.current&&M.current!==h&&(h=M.current),Te){z();continue}}Ze.push({payloadType:Qe,payload:re}),Le(),z()}}Le()}};function Zp(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Rr(){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 Xa="[Image]";function eu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function tu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Qa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function nu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function ou(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function ru(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 su(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 au=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Bh=["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"],Kn=[...au,...Bh];function Dh(e){return au.includes(e)||e.startsWith("image/")}function Ya(e){return Dh(e.type)}async function iu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ya(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 lu(e,t=Kn,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 Oh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function cu(e,t){let n=Oh(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"}Xl();var du=16e3,Nh=24e3,Fh=4096,_h=1380533830;function $h(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===_h?new Uint8Array(e,44):new Uint8Array(e)}function jh(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 Rs=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:du,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:du});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ir(Nh);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=`${jh(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 y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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(Fh,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=$h(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 Zo=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 Rs(e.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(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 Za(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(Zo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Is(e){try{return Za(e),!0}catch{return!1}}function Wr(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):Wr(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 er=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 Ql(e){if(!e)return"";let t=Uh(e);return pu(t!==null?t:e)}function Uh(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 pu(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 mu=null;var Ql=()=>mu?mu():Promise.resolve().then(()=>(gu(),fu));var qh=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Vh(e,t){return qh.some(n=>e[n]!==t[n])}function Yl(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 hu=null;var Yl=()=>hu?hu():Promise.resolve().then(()=>(mu(),gu));var Gh=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Jh(e,t){return Gh.some(n=>e[n]!==t[n])}function Zl(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 Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),bu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,vu=e=>po(e)||e===Tn,Hr=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 er(()=>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===Tn&&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 Yo(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||Ql().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 Is(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,s=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,r=this.config.clientToken,a=t.browserFallback!==!1;if(o&&s&&r)return Ql().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:s,clientToken:r,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 r&&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 s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="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(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),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(!Vh(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 Yo(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:s,contentParts:r,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?Rr():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,...s!==void 0&&{llmContent:s},...r!==void 0&&{contentParts:r},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:s,content:r,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:y,rawContent:f}=o,C={id:p??(s==="user"?Rr():s==="assistant"?yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:r,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...y!==void 0&&{voiceProcessing:y},...f!==void 0&&{rawContent:f}};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:s="",llmContent:r,id:a,createdAt:i,sequence:p}=t,d={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(d),...r!==void 0&&{llmContent:r},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let s;try{s=await o()}catch{return}let r=s.blocks.join(`
18
+ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),vu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,xu=e=>po(e)||e===Tn,Hr=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 er(()=>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===Tn&&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 Yo(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||Yl().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 Is(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 Yl().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(!Jh(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 Yo(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,f={id:a??(n==="user"?Rr():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(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:y,rawContent:f}=o,C={id:p??(r==="user"?Rr():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},...y!==void 0&&{voiceProcessing:y},...f!==void 0&&{rawContent:f}};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
- `),a=[r,n].filter(Boolean).join(`
20
+ `),a=[s,n].filter(Boolean).join(`
21
21
 
22
- `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=s.contentParts.length>0;if(i){let d=[];r&&d.push(bo(r)),d.push(...s.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(bo(a)),d.push(...s.contentParts),t.contentParts=d}else r&&(t.llmContent=a);Object.keys(s.context).length>0&&(t.mentionContext=s.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 s=Rr(),r=yo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Xa(n.contentParts)?Ja:"",i={id:s,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===s)??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:r},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 y=Yl(c,this.config.errorMessage);if(y){let f={id:r,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(f)}}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(s){if(this.status==="resuming"||this.reconnecting)return;let r=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!r){let a=Yl(s,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,r||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}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,s=!1;for(let r of this.messages)r.streaming&&r.id!==o&&(r.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(r instanceof Error?r:new Error(String(r)))}}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(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(r=>r.id===t);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let s=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===s),i={id:s,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:r};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 y=await c.json().catch(()=>null);throw new Error(y?.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(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(s=>s.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 s=t.agentMetadata?.executionId,r=t.toolCall?.name;if(!s||!r){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 y=typeof u[0]?.question=="string"?u[0].question:"";y&&(a={[y]: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,y])=>`${u}: ${Array.isArray(y)?y.join(", "):y}`).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,y)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=c[f],C=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${i}-${y}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${y}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(s,{[r]: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 r=this.webMcpEpoch;queueMicrotask(()=>{r===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(s=>s.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Tn?!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,s=Date.now(),r){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...r},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],s=[],r=new AbortController;this.webMcpResolveControllers.add(r),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 y=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Tn)return{dedupeKey:u,resumeKey:f,output:Ul(),toolMessage:p,startedAt:y,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),s.push(h);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,h.signal),M;if(!C)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await C}catch(P){let I=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));return I||this.callbacks.onError?.(P instanceof Error?P:new Error(String(P))),this.markWebMcpToolComplete(p,Ws(I?"Aborted by cancel()":bu(P)),y),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ws("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:M,toolMessage:p,startedAt:y,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:r.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===Tn?{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,Ws("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,s=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);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(h)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(h)}return}let r=`${n}:${s}`;if(this.webMcpInflightKeys.has(r)||this.webMcpResolvedKeys.has(r)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(r);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===Tn,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),y="execute",f=a;try{let h;if(d?h=Ul():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,C,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(r),this.markWebMcpToolComplete(t,h,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let C=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(y==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,Ws(C||p.aborted?"Aborted by cancel()":bu(h)),a),C||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(r),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,s){let r=await this.client.resumeFlow(t,{[n]:o},{signal:s?.signal});if(!r.ok){let a=await r.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${r.status}`)}s?.onHttpOk?.(),r.body?await this.connectStream(r.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=Xo(this.config.features?.artifacts,t.artifactType),s=Ha(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}:{}}),r=this.messages.find(a=>a.id===n);if(r){r.rawContent=s,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}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(()=>(yu(),hu)).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,s)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Yl(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(r=>r.role==="assistant"&&r.content&&!r.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=Xl(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Wr(t)}toggleReadAloud(t){let n=this.messages.find(r=>r.id===t);if(!n||n.role!=="assistant")return;let o=Xl(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.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(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,r)=>{if(r!==o)return s;let a={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let c=s.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&&vu(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),y=this.webMcpResolvedKeys.has(c),f=s.toolCall?.name,h=s.agentMetadata?.executionId===p&&s.toolCall?.id===d&&f!==void 0&&vu(f)&&s.toolCall?.status==="complete";(u||y||h)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),r=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(r)&&s!==r)return s-r;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var S=require("lucide"),Kh={activity:S.Activity,"arrow-down":S.ArrowDown,"arrow-up":S.ArrowUp,"arrow-up-right":S.ArrowUpRight,bot:S.Bot,"chevron-down":S.ChevronDown,"chevron-up":S.ChevronUp,"chevron-right":S.ChevronRight,"chevron-left":S.ChevronLeft,check:S.Check,clipboard:S.Clipboard,"clipboard-copy":S.ClipboardCopy,"code-xml":S.CodeXml,copy:S.Copy,file:S.File,"file-code":S.FileCode,"file-spreadsheet":S.FileSpreadsheet,"file-text":S.FileText,"image-plus":S.ImagePlus,loader:S.Loader,"loader-circle":S.LoaderCircle,mic:S.Mic,paperclip:S.Paperclip,"refresh-cw":S.RefreshCw,search:S.Search,send:S.Send,"shield-alert":S.ShieldAlert,"shield-check":S.ShieldCheck,"shield-x":S.ShieldX,square:S.Square,"thumbs-down":S.ThumbsDown,"thumbs-up":S.ThumbsUp,upload:S.Upload,"volume-2":S.Volume2,x:S.X,user:S.User,mail:S.Mail,phone:S.Phone,calendar:S.Calendar,clock:S.Clock,building:S.Building,"map-pin":S.MapPin,lock:S.Lock,key:S.Key,"credit-card":S.CreditCard,"at-sign":S.AtSign,hash:S.Hash,globe:S.Globe,link:S.Link,"circle-check":S.CircleCheck,"circle-x":S.CircleX,"triangle-alert":S.TriangleAlert,info:S.Info,ban:S.Ban,shield:S.Shield,"arrow-left":S.ArrowLeft,"arrow-right":S.ArrowRight,"external-link":S.ExternalLink,ellipsis:S.Ellipsis,"ellipsis-vertical":S.EllipsisVertical,menu:S.Menu,house:S.House,plus:S.Plus,minus:S.Minus,pencil:S.Pencil,trash:S.Trash,"trash-2":S.Trash2,save:S.Save,download:S.Download,share:S.Share,funnel:S.Funnel,settings:S.Settings,"rotate-cw":S.RotateCw,maximize:S.Maximize,minimize:S.Minimize,"shopping-cart":S.ShoppingCart,"shopping-bag":S.ShoppingBag,package:S.Package,truck:S.Truck,tag:S.Tag,gift:S.Gift,receipt:S.Receipt,wallet:S.Wallet,store:S.Store,"dollar-sign":S.DollarSign,percent:S.Percent,play:S.Play,pause:S.Pause,"volume-x":S.VolumeX,camera:S.Camera,image:S.Image,film:S.Film,headphones:S.Headphones,"message-circle":S.MessageCircle,"message-square":S.MessageSquare,bell:S.Bell,heart:S.Heart,star:S.Star,eye:S.Eye,"eye-off":S.EyeOff,bookmark:S.Bookmark,"calendar-days":S.CalendarDays,history:S.History,timer:S.Timer,folder:S.Folder,"folder-open":S.FolderOpen,files:S.Files,sparkles:S.Sparkles,zap:S.Zap,sun:S.Sun,moon:S.Moon,flag:S.Flag,monitor:S.Monitor,smartphone:S.Smartphone},oe=(e,t=24,n="currentColor",o=2)=>{let s=Kh[e];return s?Gh(s,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 Gh(e,t,n,o){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(o)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(r=>{if(!Array.isArray(r)||r.length<2)return;let a=r[0],i=r[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))}),s.appendChild(p)}),s}var ti={allowedTypes:Kn,maxFileSize:10*1024*1024,maxFiles:4};function Jh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Xh(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 tr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??ti.allowedTypes,maxFileSize:t.maxFileSize??ti.maxFileSize,maxFiles:t.maxFiles??ti.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:ti.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=iu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let s=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,s);continue}try{let s=await au(n),r=Qa(n)?URL.createObjectURL(n):null,a={id:Jh(),file:n,previewUrl:r,contentPart:s};this.attachments.push(a),this.renderPreview(a)}catch(s){console.error("[AttachmentManager] Failed to process file:",s)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(r=>r.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);s&&s.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=Qa(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=Xh(t.file.type),p=oe(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=lu(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 s=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let r=oe("x",10,"var(--persona-text-inverse, #ffffff)",2);r?s.appendChild(r):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(s),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 xu=/\s/;function Qh(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===""||xu.test(o)}function Yh(e,t,n="@",o="anywhere",s=!1){if(!n||t<=0||t>e.length)return null;let r=t-1;for(;r>=0;){let a=e[r];if(a===n)return Qh(e,r,o)?{triggerIndex:r,query:e.slice(r+1,t)}:null;if(a===`
24
- `||a==="\uFFFC"||!s&&xu.test(a))return null;r--}return null}function Cu(e,t,n){for(let o of n){let s=Yh(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(s)return{channel:o,match:s}}return null}function wu(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Au(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]}function Su(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",s=parseFloat(o)||40,r=Math.round(s*.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=oe(a,r,"currentColor",1.5);c?d.appendChild(c):d.textContent="+",d.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),n()}),p.appendChild(d);let u=m("div","persona-send-button-tooltip");return u.textContent=i,p.appendChild(u),{button:d,wrapper:p}}var{setLoader:_C,load:Zh}=Ar({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Zl=Zh;var{setLoader:UC,load:ey}=Ar({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Tu=ey;function Hs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=$e("span",{className:Un("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=oe(e.iconName??"at-sign",13,"currentColor",2);if(o){let s=m("span","persona-mention-token-icon");s.appendChild(o),n.appendChild(s)}return n.appendChild($e("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Eu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Au(t).filter(A=>A.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(A=>A.sources.some(W=>typeof W.matchCommand=="function")),s=A=>o.some(W=>W.trigger?W.position==="line-start"?A.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=Rr(),s=yo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Qa(n.contentParts)?Xa:"",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 y=Zl(c,this.config.errorMessage);if(y){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(f)}}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=Zl(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 y=await c.json().catch(()=>null);throw new Error(y?.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 y=typeof u[0]?.question=="string"?u[0].question:"";y&&(a={[y]: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,y])=>`${u}: ${Array.isArray(y)?y.join(", "):y}`).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,y)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=c[f],C=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${i}-${y}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${y}`,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!==Tn?!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 y=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Tn)return{dedupeKey:u,resumeKey:f,output:zl(),toolMessage:p,startedAt:y,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,h.signal),M;if(!C)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await C}catch(P){let I=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));return I||this.callbacks.onError?.(P instanceof Error?P:new Error(String(P))),this.markWebMcpToolComplete(p,Ws(I?"Aborted by cancel()":vu(P)),y),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ws("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:M,toolMessage:p,startedAt:y,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===Tn?{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,Ws("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 h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);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(h)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(h)}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===Tn,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),y="execute",f=a;try{let h;if(d?h=zl():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,C,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,h,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let C=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(y==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,Ws(C||p.aborted?"Aborted by cancel()":vu(h)),a),C||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}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=Xo(this.config.features?.artifacts,t.artifactType),r=Ba(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(()=>(bu(),yu)).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=>Zl(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=Ql(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Wr(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Ql(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&&xu(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),y=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,h=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&xu(f)&&r.toolCall?.status==="complete";(u||y||h)&&(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"),Xh={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=Xh[e];return r?Qh(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 Qh(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 ni={allowedTypes:Kn,maxFileSize:10*1024*1024,maxFiles:4};function Yh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Zh(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 tr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??ni.allowedTypes,maxFileSize:t.maxFileSize??ni.maxFileSize,maxFiles:t.maxFiles??ni.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:ni.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=lu(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 iu(n),s=Ya(n)?URL.createObjectURL(n):null,a={id:Yh(),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=Ya(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=Zh(t.file.type),p=ne(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=cu(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 Cu=/\s/;function ey(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===""||Cu.test(o)}function ty(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 ey(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
24
+ `||a==="\uFFFC"||!r&&Cu.test(a))return null;s--}return null}function wu(e,t,n){for(let o of n){let r=ty(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Au(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Su(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]}function Tu(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=Fe("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);c?d.appendChild(c):d.textContent="+",d.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),n()}),p.appendChild(d);let u=m("div","persona-send-button-tooltip");return u.textContent=i,p.appendChild(u),{button:d,wrapper:p}}var{setLoader:zC,load:ny}=Ar({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var ec=ny;var{setLoader:KC,load:oy}=Ar({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Eu=oy;function Hs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Fe("span",{className:Un("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(Fe("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Mu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Su(t).filter(A=>A.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(A=>A.sources.some(W=>typeof W.matchCommand=="function")),r=A=>o.some(W=>W.trigger?W.position==="line-start"?A.split(`
25
25
  `).some(N=>N.startsWith(W.trigger)):(W.position==="anywhere"?A:A.split(`
26
- `)[0]).startsWith(W.trigger):!1),r=(A,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:W}))}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,y=null,f=null,h=()=>{if(i)return Promise.resolve(i);if(p)return p;let A=Zl().then(W=>(i=W.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:I,emit:r}),i)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),p===A&&(p=null),null));return p=A,A},C=()=>{Tu().then(A=>{let W=A.mountInlineComposer({textarea:e.textarea,renderToken:N=>Hs(N,{render:t.renderMentionToken}),onMentionRemoved:N=>i?.untrackMention(N)});c=W.input,u=W.destroy;let $=d;$.replaceWith(W.element),d=W.element,f={next:W.element,prev:$},y?.(W.element,$),i?i.rebindComposer(W.input):p&&p.then(N=>N?.rebindComposer(W.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&C();let M=[],P=new Map;for(let A of n){if(!A.showButton)continue;let W=Su({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then($=>$?.openMenu(A.trigger))}});M.push(W),P.set(A.trigger,W.button)}let I=(A,W,$)=>{let N=P.get(W);N&&(N.setAttribute("aria-expanded",A?"true":"false"),A?N.setAttribute("aria-controls",$):N.removeAttribute("aria-controls"))};return{affordanceButtons:M.map(A=>A.wrapper),contextRow:a,handleInput:A=>{if(i){i.handleInput();return}if(!wu(A))return;let W=d,$=W.selectionStart??0;Cu(W.value,$,n)&&h().then(N=>N?.handleInput())},handleKeydown:A=>{if(i?.isMenuOpen())return i.handleKeydown(A);if(A.key==="Backspace"&&i?.hasMentions()&&!f){let W=d,$=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||$)&&i.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async A=>s(A)?(i??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>i?.clear(),prefetch:()=>{Zl().catch(()=>{})},onComposerSwap:A=>{y=A,f&&A(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let A of M)A.wrapper.remove();a.remove()}}}var Mu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];Mu(r)&&Mu(s)?n[o]=Bs(r,s):n[o]=s}return n}var cn="min(440px, calc(100vw - 24px))",ni="440px",ty={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:cn,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)"},ut={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:ty,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 ku(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function oi(e){return e?{...ut,...e,theme:ku(ut.theme,e.theme),darkTheme:ku(ut.darkTheme,e.darkTheme),launcher:{...ut.launcher,...e.launcher,dock:{...ut.launcher?.dock,...e.launcher?.dock},clearChat:{...ut.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...ut.copy,...e.copy},sendButton:{...ut.sendButton,...e.sendButton},statusIndicator:{...ut.statusIndicator,...e.statusIndicator},voiceRecognition:{...ut.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=ut.features?.artifacts,n=e.features?.artifacts,o=ut.features?.scrollToBottom,s=e.features?.scrollToBottom,r=ut.features?.scrollBehavior,a=e.features?.scrollBehavior,i=ut.features?.streamAnimation,p=e.features?.streamAnimation,d=ut.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},y=o===void 0&&s===void 0?void 0:{...o,...s},f=r===void 0&&a===void 0?void 0:{...r,...a},h=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{...ut.features,...e.features,...y!==void 0?{scrollToBottom:y}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??ut.suggestionChips,suggestionChipsConfig:{...ut.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ut.layout,...e.layout,header:{...ut.layout?.header,...e.layout?.header},messages:{...ut.layout?.messages,...e.layout?.messages,avatar:{...ut.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...ut.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...ut.layout?.slots,...e.layout?.slots}},markdown:{...ut.markdown,...e.markdown,options:{...ut.markdown?.options,...e.markdown?.options}},messageActions:{...ut.messageActions,...e.messageActions}}:ut}var ri="16px",si="transparent",ec={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"}},tc={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"}},nc={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:cn,maxWidth:ni,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ri,canvasBackground:si},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 Jt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Jt(e,o):o}function ai(e){let t={};function n(o,s){for(let[r,a]of Object.entries(o)){let i=`${s}.${r}`;if(typeof a=="string"){let p=Jt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function oc(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 Lu(e,t){let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];r&&typeof r=="object"&&!Array.isArray(r)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=Lu(r,s):n[o]=s}return n}function ny(e,t){return t?Lu(e,t):e}function Br(e,t={}){let n={palette:ec,semantic:tc,components:nc},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:ny(n.components,e?.components)};if(t.validate!==!1){let s=oc(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(r=>r.message).join(", ")}`)}if(t.plugins)for(let s of t.plugins)o=s.transform(o);return o}function ii(e){let t=ai(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"]??ri,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??si,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 s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let r=n["--persona-components-markdown-heading-h1-fontWeight"];r&&(n["--persona-md-h1-weight"]=r);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 y=d?.toggleGroup;y&&(y.gap&&(n["--persona-toggle-group-gap"]=y.gap),y.borderRadius&&(n["--persona-toggle-group-radius"]=y.borderRadius));let f=d?.artifact;if(f?.toolbar){let w=f.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"]=Jt(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(f?.tab){let w=f.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(f?.pane){let w=f.pane;if(w.toolbarBackground){let z=Jt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=z}}if(f?.card){let w=f.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(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Jt(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"]=Jt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Jt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Jt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Jt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let h=d?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Jt(e,h.background)??h.background));let C=n["--persona-surface"],M=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",I=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",W=!M||M===C,$=W?P:M,N=W?I:M;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??N,W&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$,n}var Pu={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 oy={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"}}},Ru=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ds=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",ry=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ds()},li=e=>ry(e),sy=e=>Br(e),ay=e=>{let t=Br(void 0,{validate:!1});return Br({...e,palette:{...t.palette,colors:{...oy.colors,...e?.palette?.colors}}},{validate:!1})},Co=e=>{let t=li(e),n=Ru(e?.theme),o=Ru(e?.darkTheme);return t==="dark"?ay(Bs(n??{},o??{})):sy(n)},iy=e=>ii(e),nr=(e,t)=>{let n=Co(t),o=iy(n);for(let[s,r]of Object.entries(o))e.style.setProperty(s,r);e.setAttribute("data-persona-color-scheme",li(t))},Dr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ds())});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(Ds());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 Wn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Iu(e){let t=Wn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ci(e){if(typeof e!="string")return"";let t=e.indexOf(`
27
- `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),s=o.lastIndexOf(`
28
- `);return(s===-1?o:o.slice(0,s)).split("`\u200B``").join("```")}function Os(e){let t=Iu(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(Os(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Iu(e.path);return t?t.toUpperCase():"File"}}}function Wu(e){let t=e.markdown??"";return e.file?{filename:Wn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:ci(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var rc="http://www.w3.org/2000/svg";function Hu(e){let t=document.createElementNS(rc,"svg");t.setAttribute("class",Un("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(rc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(rc,"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 s of t){let r=m("span","persona-tool-char");r.style.setProperty("--char-index",String(o)),r.textContent=s===" "?"\xA0":s,e.appendChild(r),o++}return o};function Bu(e,t,n){let o=n?.loadingAnimation??"shimmer",s=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",`${s}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",`${s}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 sc="persona-artifact-status-label",Du="persona-artifact-status-detail",Ou="data-artifact-status-label",ac=new Map,Nu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Or(e){e&&ac.delete(e)}function ly(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?wo(t):e.artifactType==="component"?"Component":"Document"}function Nr(e,t,n){let o=ly(e),s=`Generating ${o.toLowerCase()}...`,r=t?.statusLabel;if(typeof r=="string")return{label:r};if(typeof r!="function")return{label:s};let a=e.id,i=ac.get(a);e.status!=="complete"&&i===void 0&&(i=Nu(),ac.set(a,i));let p=i===void 0?0:Math.max(0,Nu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,y=d||c===""?0:c.split(`
29
- `).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:y,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=r(h);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:s}}catch{return{label:s}}}function cy(e){e.className=sc,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 or(e,t,n){let o=e.querySelector(`:scope > .${sc}`);o||(o=m("span",sc),e.appendChild(o)),o.getAttribute(Ou)!==t.label&&(cy(o),Bu(o,t.label,n),o.setAttribute(Ou,t.label));let s=e.querySelector(`:scope > .${Du}`),r=t.detail;r?(s||(s=m("span",Du),e.appendChild(s)),s.textContent!==r&&(s.textContent=r)):s&&s.remove()}var dy={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"},py=15e4,di={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 uy(e,t){let n=(e||"").trim().toLowerCase();if(n&&di[n])return di[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let s=t.slice(o+1).toLowerCase();if(di[s])return di[s]}}return null}function pi(e,t){let n=[],o=0,s=0,r=a=>{a>s&&n.push({type:"plain",value:e.slice(s,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){r(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,s=o,a=!0;break}}a||(o+=1)}return r(e.length),n}var fy=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"]),gy=[{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=>fy.has(e)?"keyword":"plain"}];function Fu(e){return pi(e,gy)}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 hy(e){let t=pi(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 s=t[o];s&&s.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var yy=[{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 _u(e){let t=pi(e,yy),n="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(s.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===",")&&(s.type="property")}let r=s.value.replace(/\s+$/,"");r&&(n=r[r.length-1])}return t}var by=[{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 vy(e){let t=[],n=(r,a)=>{a&&t.push({type:r,value:a})},o=e.length,s=0;for(;s<o;){if(e.startsWith("<!--",s)){let a=e.indexOf("-->",s+4),i=a===-1?o:a+3;n("comment",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&e[s+1]==="!"){let a=e.indexOf(">",s),i=a===-1?o:a+1;n("tag",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&/[A-Za-z/]/.test(e[s+1]||"")){let a=e.indexOf(">",s),i=a===-1?o:a+1,p=e.slice(s,i);for(let c of pi(p,by))t.push(c);s=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),y=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(s)),f=y?s+y.index:o,h=e.slice(s,f),C=c==="script"?Fu(h):_u(h);for(let M of C)t.push(M);s=f}continue}let r=e.indexOf("<",s);if(r===s)n("plain",e[s]),s+=1;else{let a=r===-1?o:r;n("plain",e.slice(s,a)),s=a}}return t}function xy(e,t){switch(t){case"html":return vy(e);case"css":return _u(e);case"js":return Fu(e);case"json":return hy(e)}}function Cy(e){let t=Ip(),n=m("span","persona-code-line"),o=(s,r)=>{if(!r)return;let a=dy[s];if(a){let i=m("span",a);i.textContent=r,n.appendChild(i)}else n.appendChild(document.createTextNode(r))};for(let s of e){let r=s.value.split(`
30
- `);for(let a=0;a<r.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
31
- `)),n=m("span","persona-code-line")),o(s.type,r[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function $u(e,t,n){let o=e.length<=py?uy(t,n):null,s=o?xy(e,o):[{type:"plain",value:e}];return Cy(s)}var Dt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,So=zt+1;function To(e){let{items:t,onSelect:n,anchor:o,position:s="bottom-left",portal:r}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),r?(a.style.position="fixed",a.style.zIndex=String(So)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let M=oe(f.icon,16,"currentColor",1.5);M&&h.appendChild(M)}let C=document.createElement("span");C.textContent=f.label,h.appendChild(C),h.addEventListener("click",M=>{M.stopPropagation(),c(),n(f.id)}),a.appendChild(h)}let i=null;function p(){if(!r)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!a.contains(h.target)&&!o.contains(h.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function y(){c(),a.remove()}return r&&r.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:y}}function mt(e){let{icon:t,label:n,size:o,strokeWidth:s,className:r,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(r?" "+r:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=oe(t,o??16,"currentColor",s??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 Gn(e){let{icon:t,label:n,variant:o="default",size:s="sm",iconSize:r,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+s,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let y=oe(t,r??14,"currentColor",2);y&&c.appendChild(y)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[y,f]of Object.entries(p))c.setAttribute(y,f);return c}function Jn(e){let{items:t,selectedId:n,onSelect:o,className:s}=e,r=m("div","persona-toggle-group"+(s?" "+s:""));r.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=mt({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}),r.appendChild(u)}function d(c){a=c,p()}return{element:r,setSelected:d}}function ui(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:s,position:r="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=oe(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 y=To({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),s(f)},anchor:d,position:r,portal:a});return a||d.appendChild(y.element),d.addEventListener("click",f=>{f.stopPropagation();let h=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),y.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),y.show()},close:()=>{d.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let f=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),d.remove()}}}var fi="persona-artifact-custom-action-btn";function Fr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let s="persona-label-btn persona-label-btn--sm "+fi+(n?" persona-artifact-doc-copy-btn":"");o=m("button",s)}else{let s="persona-icon-btn "+fi+(n?" persona-artifact-doc-icon-btn":"");o=m("button",s)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let s=e.icon();s&&o.appendChild(s)}catch{}if(e.showLabel){let s=m("span");s.textContent=e.label,o.appendChild(s)}}else e.showLabel||!e.icon?o=Gn({icon:e.icon,label:e.label,className:fi+(n?" persona-artifact-doc-copy-btn":"")}):o=mt({icon:e.icon,label:e.label,className:fi+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ns(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",s=n?Wn(n.path):o,r=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 ${s} in artifact panel`),r&&d.setAttribute("data-open-artifact",r);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 y=document.createElement("div");y.className="persona-truncate persona-text-sm persona-font-medium",y.style.color="var(--persona-text, #1f2937)",y.textContent=s;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let h=t?.config?.features?.artifacts,C={id:r,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},M=Nr(C,h,"card");or(f,M,h)}else r&&Or(r),f.textContent=p;if(u.append(y,f),d.append(c,u),a==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let M={artifactId:r||null,title:s,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let P of h)try{if(P.visible===void 0||P.visible(M)){let I=Fr(P);I.setAttribute("data-artifact-custom-action",P.id),I.className=`${I.className} persona-flex-shrink-0`,d.append(I)}}catch{}}let C=Gn({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${s}`,C.setAttribute("data-download-artifact",r),d.append(C)}return d}var gi=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>ju(e,t)});if(i)return i}return ju(e,t)};var Eo=new WeakMap;function ic(e,t,n){if(t.length===0)return;let o=new Map(t.map(s=>[s.id,s]));e.querySelectorAll("[data-artifact-inline]").forEach(s=>{let r=Eo.get(s);if(!r)return;let a=o.get(s.getAttribute("data-artifact-inline")??"");a&&r(a,n)})}function Ku(e){return Eo.has(e)}function wy(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 r=e.componentProps,a=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let s=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:"",...s?{file:s}:{}}}function Uu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Wn(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 Ay(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 zu=180,Sy=240,Ty=.8,Ey=300,My=500,ky="cubic-bezier(0.2, 0, 0, 1)",qu=240,Ly=.35;function Py(e,t,n){let{swap:o,onSettled:s}=n,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(!t||!e.isConnected||r||typeof e.animate!="function"){o(),s();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:zu,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(),s();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),s();return}let d=Math.abs(t-p),c=Math.round(Math.min(My,Math.max(Ey,Sy+d*Ty))),u=Math.round(c*Ly),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=y?y.animate([{opacity:0},{opacity:1}],{duration:qu,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:ky});e.style.height=`${p}px`;let C=!1,M=()=>{C||(C=!0,i(),s())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(c,u+qu)+120)},zu)}function Ry(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 Fs="--persona-artifact-inline-body-height";function Iy(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",s=320,r=320,a=t?.height;typeof a=="number"||a==="auto"?(s=a,r=a):a&&typeof a=="object"&&(s=a.streaming??320,r=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 y=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:s,completeHeight:r,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:y,completeDisplay:f}}function Vu(e,t){let n=wy(e),o=t.config?.features?.artifacts,{chromeEnabled:s,showCopy:r,showExpand:a,showViewToggle:i}=Ry(o),p=o?.inlineActions??[],d=Iy(o),c=d.completeDisplay==="card",u=null,y=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=Z=>gi(Ay(Z),t),C=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Fs),f.replaceChildren(h(Z)),Eo.set(f,de=>{f.replaceChildren(h(de))})};if(c&&n.status==="complete")return C(n),f;let M=mi(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),P=m("div","persona-artifact-inline-body");P.appendChild(M.el);let I=Z=>{let de=Z.status!=="complete",ee=de?d.streamingHeight:d.completeHeight,Ce=typeof ee=="number";Ce?f.style.setProperty(Fs,`${ee}px`):f.style.removeProperty(Fs);let he=!!M.el.querySelector(".persona-code-pre"),fe=!!M.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");P.classList.toggle("persona-artifact-content-flush",he),P.classList.toggle("persona-artifact-inline-body--sized",Ce&&fe),P.classList.toggle("persona-artifact-inline-body--cap",!de&&!fe&&typeof d.completeHeight=="number")},A=n.status,W=(Z,de)=>{A!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(Fs,`${d.completeHeight}px`):f.style.removeProperty(Fs),Ju(P,de?.suppressTransition?"none":d.transition,Z.id,()=>{M.update(Z),I(Z)})):M.update(Z),I(Z),A=Z.status};I(n);let $=d.overflow==="clip"&&a&&!!n.id;if($&&(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 ${Uu(n).title} in panel`)),!s)return f.appendChild(P),Eo.set(f,W),f;let N=m("div","persona-artifact-inline-chrome");N.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=oe("file-text",16,"currentColor",2);V&&z.appendChild(V);let Y=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=m("span","persona-artifact-inline-type");w.append(z,Y,O);let U=m("div","persona-artifact-inline-chrome-actions"),me=m("span","persona-flex persona-items-center persona-gap-1"),be=()=>u??d.viewMode,Me=i?Jn({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:be(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let de=Z==="source"?"source":"rendered";de!==be()&&(u=de,M.update(y),I(y))}}):null,Oe=r?mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Oe&&n.id&&Oe.setAttribute("data-copy-artifact",n.id);let ae=a?mt({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),U.appendChild(me),Me&&U.appendChild(Me.element),Oe&&U.appendChild(Oe),ae&&U.appendChild(ae),N.append(w,U),f.append(N,P);let ve=Z=>{let{title:de,typeLabel:ee}=Uu(Z);Y.textContent=de,Y.title=de,$&&P.setAttribute("aria-label",`Open ${de} in panel`);let Ce=Z.status!=="complete";if(Ce){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let he=Nr(Z,o,"inline-chrome");or(O,he,o)}else Or(Z.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=ee;if(Oe&&Oe.classList.toggle("persona-hidden",Ce),Me){let he=Z.artifactType==="markdown"?Z.file:void 0,fe=!1;if(!Ce&&he&&d.viewMode!=="source"){let Re=Os(he);Re==="markdown"?fe=!0:(Re==="html"||Re==="svg")&&(fe=o?.filePreview?.enabled!==!1)}Me.element.classList.toggle("persona-hidden",!fe),Me.setSelected(be())}if(me.replaceChildren(),!Ce&&p.length>0){let he=Ns(Z);if(he)for(let fe of p)try{if(fe.visible===void 0||fe.visible(he)){let Re=Fr(fe,{documentChrome:!0});Re.setAttribute("data-artifact-custom-action",fe.id),Re.classList.add("persona-flex-shrink-0"),me.appendChild(Re)}}catch{}}};return ve(n),Eo.set(f,(Z,de)=>{if(c&&A!=="complete"&&Z.status==="complete"){let ee=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let Ce=Z,he=!1,fe=Re=>{Ce=Re,he=!0};Eo.set(f,fe),Py(f,ee,{swap:()=>{C(Ce),he=!1,Eo.set(f,fe)},onSettled:()=>{he?C(Ce):Eo.set(f,Re=>{f.replaceChildren(h(Re))})}});return}(Z.status!=="complete"||Z.id!==y.id)&&(u=null),y=Z,W(Z,de),ve(Z)}),f}var Gu=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>Vu(e,t)});if(i)return i}return Vu(e,t)};var lc=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)})}},En=new lc;En.register("PersonaArtifactCard",gi,{bubbleChrome:!1});En.register("PersonaArtifactInline",Gu,{bubbleChrome:!1});function _s(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ci(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var cc=!1;function Wy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Ju(e,t,n,o){let s=typeof document<"u"?document.startViewTransition:void 0,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(t!=="auto"||!e||typeof s!="function"||cc||r){o();return}cc=!0;let a=Wy(n);e.style.setProperty("view-transition-name",a);let i=()=>{cc=!1,e.style.removeProperty("view-transition-name")};try{s.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Hy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",By="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Dy(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 Oy(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 Ny=220;function Fy(){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 _y(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 $y(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 s=m("div","persona-artifact-frame-loading-indicator");s.appendChild(Hu());let r=null;return n.label!==!1&&(r=m("div","persona-artifact-frame-loading-text"),r.textContent=n.label,s.appendChild(r)),o.appendChild(s),{el:o,revealLabel:()=>{r&&r.classList.add("persona-artifact-frame-loading-text--visible")}}}function jy(e,t,n,o,s,r){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(A=>clearTimeout(A)),d.clear()},u=(A,W)=>{let $=setTimeout(()=>{d.delete($),A()},W);d.add($)},y=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let A=$y(s,r,o);a=A.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(y,Ny))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):t.removeEventListener("load",I)},M=()=>{if(p||(p=!0,C(),c(),!a))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-i));A>0?u(h,A):h()};function P(A){if(n===null)return;let W=A.data;!W||W.persona!=="artifact-preview-ready"||W.token!==n||A.source===t.contentWindow&&M()}function I(){let A=W=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>W()):setTimeout(W,0)};A(()=>A(()=>M()))}return u(f,o.delayMs),u(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):t.addEventListener("load",I),()=>{p=!0,c(),C(),y()}}function mi(e,t){let{config:n}=t,o=t.registry??En,s=t.bodyLayout,r=n.markdown?Jo(n.markdown):null,a=Tr(n.sanitize),i=e,p=!1,d=ae=>{let ve=jn()!==null;r&&!ve&&!p&&(p=!0,Sr(()=>Oe(i)));let Z=r?r(ae):Rn(ae);return r&&ve&&a?a(Z):Z},c=m("div","persona-artifact-preview-body"),u=null,y=null,f=null,h=()=>{f&&(f(),f=null),u=null,y=null},C=null,M=null,P=null,I=!1,A=()=>{C=null,M=null,P=null,I=!1},W=null,$=null,N=()=>{W=null,$=null},w=40,z=0,V=ae=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ae()):setTimeout(ae,0),Y=ae=>ae.scrollHeight-ae.clientHeight-ae.scrollTop<=w,O=ae=>{if(!s)return;let ve=ae.scrollHeight-ae.clientHeight>1,Z=ae.scrollHeight-ae.clientHeight-ae.scrollTop;ae.classList.toggle("persona-artifact-fade-top",s.fadeTop&&ve&&ae.scrollTop>1),ae.classList.toggle("persona-artifact-fade-bottom",s.fadeBottom&&ve&&Z>1)},U=ae=>{z||(z=V(()=>{z=0,ae.scrollTop=ae.scrollHeight,O(ae)}))},me=(ae,ve,Z,de)=>{let ee=!!s,Ce=Z.id+"|"+(ee?"w":"p");if(!C||P!==Ce||C.parentElement!==c){h(),N(),c.replaceChildren();let Re=m("pre",Hy+" persona-code-pre"),Ne=m("code","persona-code");if(Re.appendChild(Ne),ee){let ze=m("div","persona-artifact-source-window");if(ze.appendChild(Re),c.appendChild(ze),!(s?.overflow==="clip")&&typeof ze.addEventListener=="function"){let Ae=()=>ze.scrollHeight-ze.clientHeight>1;ze.addEventListener("scroll",()=>{Y(ze)&&(I=!1),O(ze)},{passive:!0}),ze.addEventListener("wheel",Pe=>{Ae()&&Pe.deltaY<0&&(I=!0)},{passive:!0}),ze.addEventListener("touchmove",()=>{Ae()&&(I=!0)},{passive:!0})}C=ze}else c.appendChild(Re),C=Re;M=Ne,P=Ce}let he=ee?C:null;he&&(he.classList.toggle("persona-artifact-source-window--fixed",de),he.classList.toggle("persona-artifact-source-window--clip",de&&s?.overflow==="clip"));let fe=he?Y(he):!0;if(M.replaceChildren($u(ae,ve?.language,ve?.path)),he){let Re=Z.status!=="complete";de&&Re&&s?.followOutput&&!I&&fe?U(he):Re||(I=!1),O(he)}},be=ae=>{h(),A(),N(),c.replaceChildren();let ve=m("div",By);ve.innerHTML=d(ae),c.appendChild(ve)},Me=ae=>{let ve=ae.id,Z=n.features?.artifacts,de=Nr(ae,Z,"status-body");if(W&&$===ve&&W.parentElement===c){let he=W.querySelector(".persona-artifact-status-view-text");he&&or(he,de,Z);return}h(),A(),c.replaceChildren();let ee=m("div","persona-artifact-status-view"),Ce=m("div","persona-artifact-status-view-text");or(Ce,de,Z),ee.appendChild(Ce),c.appendChild(ee),W=ee,$=ve},Oe=ae=>{i=ae;let ve=t.resolveViewMode?.(ae)??s?.viewMode??"rendered",Z=ae.artifactType==="markdown"?ae.file:void 0,de=ae.status!=="complete";de||Or(ae.id);let ee=de?s?.streamingHeight:s?.completeHeight,Ce=!!s&&typeof ee=="number";if(s?.streamingView==="status"&&de){Me(ae);return}if(Z){let fe=ci(ae.markdown??""),Re=Os(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&ve==="rendered"&&Ne&&(Re==="html"||Re==="svg")){let Fe=ae.id+"\0"+fe;if(u&&y===Fe&&u.parentElement===c)return;A(),N(),h(),c.replaceChildren();let Ae=n.features?.artifacts?.filePreview,Pe=Ae?.iframeSandbox??"allow-scripts";!Ae?.dangerouslyAllowSameOrigin&&Pe.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."),Pe=Pe.split(/\s+/).filter(bt=>bt&&bt!=="allow-same-origin").join(" "));let rt=Oy(Ae?.loading),le=m("div","persona-artifact-frame"),Ie=m("iframe","persona-artifact-iframe");Ie.setAttribute("sandbox",Pe),Ie.setAttribute("data-artifact-id",ae.id);let Ct=null;rt.enabled&&rt.injectReadySignal?(Ct=Fy(),Ie.srcdoc=fe+_y(Ct)):Ie.srcdoc=fe,le.appendChild(Ie),c.appendChild(le),rt.enabled&&(f=jy(le,Ie,Ct,rt,ae.id,n)),u=le,y=Fe;return}if(h(),!de&&Re==="markdown"&&ve==="rendered"){be(fe);return}me(fe,{language:Z.language,path:Z.path},ae,Ce);return}if(ae.artifactType==="markdown"){if(ve==="source"){h(),me(ae.markdown??"",void 0,ae,Ce);return}be(ae.markdown??"");return}h(),A(),N(),c.replaceChildren();let he=ae.component?o.get(ae.component):void 0;if(he){let Re={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=he(ae.props??{},Re);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(Dy(ae))};return Oe(e),{el:c,update(ae){Oe(ae)}}}var Xu=require("idiomorph"),hi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Xu.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,r){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return r instanceof HTMLElement&&r.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(r instanceof HTMLElement&&!r.hasAttribute("data-preserve-animation"))return;if(r instanceof HTMLElement&&r.hasAttribute("data-preserve-animation")){let a=s.textContent??"",i=r.textContent??"";if(a!==i)return}return!1}}}}})};var Qu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var dc={index:-1,draft:""};function Yu(e){let{direction:t,history:n,currentValue:o,atStart:s,state:r}=e,a=r.index!==-1;if(n.length===0)return{handled:!1,state:r};if(t==="up"){if(!a&&!s)return{handled:!1,state:r};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(r.index>0){let i=r.index-1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,state:r}}if(!a)return{handled:!1,state:r};if(r.index<n.length-1){let i=r.index+1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,value:r.draft,state:{index:-1,draft:r.draft}}}function Zu(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 ef(){return new Map}function tf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function nf(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function of(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function yi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Hn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Mo(e,t){return Hn(e)-e.scrollTop<=t}function bi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:s,userScrollThreshold:r,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<r?{action:"none",delta:c,nextLastScrollTop:n}:!t&&s&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!s?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function vi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&o?"resume":"none"}function rf(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sf(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 af(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var $s={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Uy=["pre","code","a","script","style"],xi=e=>({type:e?.type??$s.type,placeholder:e?.placeholder??$s.placeholder,speed:e?.speed??$s.speed,duration:e?.duration??$s.duration,buffer:e?.buffer??$s.buffer}),cf=[{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"}],js=new Map;for(let e of cf)js.set(e.name,e);var df=e=>{js.set(e.name,e)},pf=e=>{cf.some(t=>t.name===e)||js.delete(e)},uf=()=>Array.from(js.keys()),_r=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:js.get(e)??null,Ci=(e,t,n,o,s)=>{if(!s)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let r=e.search(/\s(?=\S*$)/);return r<0?"":e.slice(0,r)}if(t==="line"){let r=e.lastIndexOf(`
33
- `);return r<0?"":e.slice(0,r)}return e},zy=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${o}`,s.style.setProperty("--char-index",String(o)),s.textContent=t,s},qy=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${o}`,s.style.setProperty("--word-index",String(o)),s.textContent=t,s},pc=/\s/,Vy=(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},Ky=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=0;for(;i<r.length;)if(pc.test(r[i])){let p=i;for(;p<r.length&&pc.test(r[p]);)p+=1;a.appendChild(o.createTextNode(r.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<r.length&&!pc.test(r[d]);)p.appendChild(zy(o,r[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}s.replaceChild(a,e)},Gy=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=r.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(qy(o,p,t,n.value)),n.value+=1));s.replaceChild(a,e)},Us=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let s=document.createElement("div");s.innerHTML=e;let r=new Set((o?.skipTags??Uy).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)Vy(p,r)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Ky:Gy;for(let u of i)c(u,n,d);return s.innerHTML},wi=(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},zs=(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},lf=new WeakMap,Jy=(e,t)=>{if(!e.styles)return;let n=lf.get(t);if(n||(n=new Set,lf.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},uc=new WeakMap,Xy=(e,t)=>{if(!e.onAttach)return;let n=uc.get(t);if(n||(n=new Map,uc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},ff=e=>{let t=uc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ai=(e,t)=>{Jy(e,t),Xy(e,t)};function fc(e,t=zt){let n=e.style.position,o=e.style.zIndex,s=e.style.isolation,r=getComputedStyle(e),a=r.position==="static"||r.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=s}}var qs=0,ko=null;function gc(e=document){if(qs++,qs===1){let n=e.body,s=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ko={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,qs=Math.max(0,qs-1),qs===0&&ko)){let n=e.body,o=e.defaultView??window;n.style.overflow=ko.originalOverflow,n.style.position=ko.originalPosition,n.style.top=ko.originalTop,n.style.width=ko.originalWidth,o.scrollTo(0,ko.scrollY),ko=null}}}var Vs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Wt=e=>(e?.launcher?.mountMode??"floating")==="docked",Lo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",tn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Vs.side,width:t?.width??Vs.width,animate:t?.animate??Vs.animate,reveal:t?.reveal??Vs.reveal,maxHeight:t?.maxHeight??Vs.maxHeight}};var Mn={"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 Qy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Qy,buttonSize:s,iconSize:r="28px"}=t,a=e?.launcher??{},i=s??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",y=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),h=$e("button",{className:Un("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Xt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=oe(u,r,"currentColor",1);if(C?(C.style.display="block",h.appendChild(C)):h.textContent=y,p.appendChild(h),c&&d){let M=null,P=()=>{if(M)return;let A=h.ownerDocument,W=A.body;if(!W)return;M=In(A,"div","persona-clear-chat-tooltip"),M.textContent=d;let $=In(A,"div");$.className="persona-clear-chat-tooltip-arrow",M.appendChild($);let N=h.getBoundingClientRect();M.style.position="fixed",M.style.zIndex=String(So),M.style.left=`${N.left+N.width/2}px`,M.style.top=`${N.top-8}px`,M.style.transform="translate(-50%, -100%)",W.appendChild(M)},I=()=>{M&&M.parentNode&&(M.parentNode.removeChild(M),M=null)};p.addEventListener("mouseenter",P),p.addEventListener("mouseleave",I),h.addEventListener("focus",P),h.addEventListener("blur",I),p._cleanupTooltip=()=>{I(),p.removeEventListener("mouseenter",P),p.removeEventListener("mouseleave",I),h.removeEventListener("focus",P),h.removeEventListener("blur",I)}}return{button:h,wrapper:p}},Yy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ti=(e,t={})=>{let{wrapperClassName:n=Yy,buttonSize:o,iconSize:s="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??"",y=a.borderColor??"",f=a.borderRadius??"",h=a.paddingX??"",C=a.paddingY??"",M=a.tooltipText??"Clear chat",P=a.showTooltip??!0,I=m("div",n),A=!!(u||y),W=$e("button",{className:Un("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:d||Xt.actionIconColor,backgroundColor:c||void 0,border:A?`${u||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),$=oe(p,s,"currentColor",1);if($&&($.style.display="block",W.appendChild($)),I.appendChild(W),P&&M){let N=null,w=()=>{if(N)return;let V=W.ownerDocument,Y=V.body;if(!Y)return;N=In(V,"div","persona-clear-chat-tooltip"),N.textContent=M;let O=In(V,"div");O.className="persona-clear-chat-tooltip-arrow",N.appendChild(O);let U=W.getBoundingClientRect();N.style.position="fixed",N.style.zIndex=String(So),N.style.left=`${U.left+U.width/2}px`,N.style.top=`${U.top-8}px`,N.style.transform="translate(-50%, -100%)",Y.appendChild(N)},z=()=>{N&&N.parentNode&&(N.parentNode.removeChild(N),N=null)};I.addEventListener("mouseenter",w),I.addEventListener("mouseleave",z),W.addEventListener("focus",w),W.addEventListener("blur",z),I._cleanupTooltip=()=>{z(),I.removeEventListener("mouseenter",w),I.removeEventListener("mouseleave",z),W.removeEventListener("focus",w),W.removeEventListener("blur",z)}}return{button:W,wrapper:I}};var Xt={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))"},Xn=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)))"}}),s=t?.launcher??{},r=s.headerIconSize??"48px",a=s.closeButtonPlacement??"inline",i=s.headerIconHidden??!1,p=s.headerIconName,d=$e("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:r,width:r,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 $=parseFloat(r)||24,N=oe(p,$*.6,"currentColor",1);N?d.replaceChildren(N):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let $=m("img");$.src=t.launcher.iconUrl,$.alt="",$.className="persona-rounded-xl persona-object-cover",$.style.height=r,$.style.width=r,d.replaceChildren($)}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:Xt.titleColor}}),y=$e("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor}});c.append(u,y),i?o.append(c):o.append(d,c);let f=s.clearChat??{},h=f.enabled??!0,C=f.placement??"inline",M=null,P=null;if(h){let N=Ti(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=N.button,P=N.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&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:A,wrapper:W}=Si(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(W),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:y,closeButton:A,closeButtonWrapper:W,clearChatButton:M,clearChatButtonWrapper:P}},rr=(e,t,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",r=o.clearChat?.placement??"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&r==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var mc=e=>{let t=Xn({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",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Zy(e,t,n){if(t?.length)for(let o of t){let s=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(s.type="button",s.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let r=oe(o.icon,14,"currentColor",2);r&&s.appendChild(r)}else o.label&&(s.textContent=o.label);if(o.menuItems?.length){let r=m("div","persona-relative");r.appendChild(s);let a=To({items:o.menuItems,onSelect:i=>n?.(i),anchor:r,position:"bottom-left"});r.appendChild(a.element),s.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(r)}else s.addEventListener("click",()=>n?.(o.id)),e.appendChild(s)}}var hc=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:r}=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=s?.titleMenu,d,c;if(p)d=ui({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Xt.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=Xt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Zy(d,s?.trailingActions,s?.onAction??r),s?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let A=s.onTitleClick;d.addEventListener("click",W=>{W.target.closest("button")||A()}),d.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),A())})}let I=s?.titleRowHover;I&&(d.style.borderRadius=I.borderRadius??"10px",d.style.padding=I.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=I.background??"",d.style.borderColor=I.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",y=m("div",""),f=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");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Xt.actionIconColor;let h=a.closeButtonIconName??"x",C=oe(h,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),y.appendChild(f),i.appendChild(y);let M=m("div");M.style.display="none";let P=m("span");return P.style.display="none",{header:i,iconHolder:M,headerTitle:c,headerSubtitle:P,closeButton:f,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},Ei={default:mc,minimal:hc},yc=e=>Ei[e]??Ei.default,$r=(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",r=yc(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&&(r.iconHolder.style.display="none"),t.showTitle===!1&&(r.headerTitle.style.display="none"),t.showSubtitle===!1&&(r.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(r.closeButton.style.display="none"),t.showClearChat===!1&&r.clearChatButtonWrapper&&(r.clearChatButtonWrapper.style.display="none")),r};var Mi=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 s=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},r=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,s());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:r}},ki=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",s=t.iconName,r=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",y=t.backgroundColor,f=t.textColor,h=m("div","persona-send-button-wrapper"),C=$e("button",{className:Un("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&&!y&&"persona-bg-persona-primary",!n&&!f&&"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?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&y||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}}),M=null,P=null;if(n){let $=parseFloat(u)||24,N=f?.trim()||"currentColor";s?(M=oe(s,$,N,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,P=oe(r,$,N,2)}else C.textContent=p;let I=null;c&&a&&(I=m("div","persona-send-button-tooltip"),I.textContent=a,h.appendChild(I)),C.setAttribute("aria-label",a),h.appendChild(C);let A="send";return{button:C,wrapper:h,setMode:$=>{if($===A)return;A=$;let N=$==="stop"?i:a;if(C.setAttribute("aria-label",N),I&&(I.textContent=N),n){if(M&&P){let w=$==="stop"?P:M;C.replaceChildren(w)}}else C.textContent=$==="stop"?d:p}}},Li=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=t.provider?.type==="runtype";if(!(o||s))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,y=m("div","persona-send-button-wrapper"),f=$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":"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=oe(i,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",y.appendChild(f);let M=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&M){let I=m("div","persona-send-button-tooltip");I.textContent=M,y.appendChild(I)}return{button:f,wrapper:y}},Pi=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 s=m("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=(t.allowedTypes??Kn).join(","),s.multiple=(t.maxFiles??4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let r=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=oe(r,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",h=>{h.preventDefault(),s.click()}),d.appendChild(c);let y=t.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=y,d.appendChild(f),{button:c,wrapper:d,input:s,previewsContainer:o}},Ri=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 s=t.visible??!0;o.style.display=s?"":"none";let r=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=r,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=r;return o},Ii=()=>$e("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var jr=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=Ii(),s=$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:r,attachAutoResize:a}=Mi(t);a();let i=ki(t),p=Li(t),d=Pi(t),c=Ri(t);d&&(d.previewsContainer.style.gap="8px",s.append(d.previewsContainer,d.input)),s.append(r);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":""}}),y=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&y.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),u.append(y,f),s.append(u),s.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&r.focus()}),n.append(o,s,c),{footer:n,suggestions:o,composerForm:s,textarea:r,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:y,rightActions:f,setSendButtonMode:i.setMode}};var gf=()=>{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=oe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),s=m("span","persona-pill-peek__caret"),r=oe("chevron-up",16,"currentColor",1.5);return r&&s.appendChild(r),e.append(t,o,s),{root:e,textNode:o}},mf=e=>{let{config:t}=e,n=$e("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ii(),s=Ri(t);s.style.display="none";let{textarea:r,attachAutoResize:a}=Mi(t);r.style.maxHeight="100px",a();let i=ki(t),p=Li(t),d=Pi(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 y=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&y.append(p.wrapper),y.append(i.wrapper),c.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&r.focus()}),d&&c.append(d.input),c.append(u,r,y),d&&n.append(d.previewsContainer),n.append(o,c,s);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:y,setSendButtonMode:i.setMode}};var hf=e=>{let t=e?.launcher?.enabled??!0,n=Wt(e);if(Lo(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 y=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",u.appendChild(y);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??zt),{wrapper:u,panel:y,pillRoot:f}}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"),y=e?.launcher?.width??"100%";return c.style.width=y,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let s=e?.launcher??{},r=s.position&&Mn[s.position]?Mn[s.position]:Mn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${r} 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??cn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},eb=(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:s}=Si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let r=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(r){let W=Ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=W.button,i=W.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."}),y=$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),f=m("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(y.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(y,f);let M=$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=mf({config:e}),{root:I,textNode:A}=gf();return n.append(p,s,d,M),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:f,composerOverlay:M,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:s,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:I,peekTextNode:A}},yf=(e,t=!0)=>{if(Lo(e))return eb(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,s=e?.layout?.showHeader!==!1,r=o?$r(e,o,{showClose:t}):Xn({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:Wt(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 f=jr({config:e}),h=e?.layout?.showFooter!==!1;s?rr(n,r,e):(r.header.style.display="none",rr(n,r,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 h||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:p,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var bc=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
26
+ `)[0]).startsWith(W.trigger):!1),s=(A,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:W}))}catch{}},a=Fe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,y=null,f=null,h=()=>{if(i)return Promise.resolve(i);if(p)return p;let A=ec().then(W=>(i=W.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:I,emit:s}),i)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),p===A&&(p=null),null));return p=A,A},C=()=>{Eu().then(A=>{let W=A.mountInlineComposer({textarea:e.textarea,renderToken:N=>Hs(N,{render:t.renderMentionToken}),onMentionRemoved:N=>i?.untrackMention(N)});c=W.input,u=W.destroy;let $=d;$.replaceWith(W.element),d=W.element,f={next:W.element,prev:$},y?.(W.element,$),i?i.rebindComposer(W.input):p&&p.then(N=>N?.rebindComposer(W.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&C();let M=[],P=new Map;for(let A of n){if(!A.showButton)continue;let W=Tu({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then($=>$?.openMenu(A.trigger))}});M.push(W),P.set(A.trigger,W.button)}let I=(A,W,$)=>{let N=P.get(W);N&&(N.setAttribute("aria-expanded",A?"true":"false"),A?N.setAttribute("aria-controls",$):N.removeAttribute("aria-controls"))};return{affordanceButtons:M.map(A=>A.wrapper),contextRow:a,handleInput:A=>{if(i){i.handleInput();return}if(!Au(A))return;let W=d,$=W.selectionStart??0;wu(W.value,$,n)&&h().then(N=>N?.handleInput())},handleKeydown:A=>{if(i?.isMenuOpen())return i.handleKeydown(A);if(A.key==="Backspace"&&i?.hasMentions()&&!f){let W=d,$=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||$)&&i.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(i??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>i?.clear(),prefetch:()=>{ec().catch(()=>{})},onComposerSwap:A=>{y=A,f&&A(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let A of M)A.wrapper.remove();a.remove()}}}var ku=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(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];ku(s)&&ku(r)?n[o]=Bs(s,r):n[o]=r}return n}var ln="min(440px, calc(100vw - 24px))",oi="440px",ry={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:ln,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)"},dt={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:ry,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 Lu(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function Br(e){return e?{...dt,...e,theme:Lu(dt.theme,e.theme),darkTheme:Lu(dt.darkTheme,e.darkTheme),launcher:{...dt.launcher,...e.launcher,dock:{...dt.launcher?.dock,...e.launcher?.dock},clearChat:{...dt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...dt.copy,...e.copy},sendButton:{...dt.sendButton,...e.sendButton},statusIndicator:{...dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...dt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=dt.features?.artifacts,n=e.features?.artifacts,o=dt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=dt.features?.scrollBehavior,a=e.features?.scrollBehavior,i=dt.features?.streamAnimation,p=e.features?.streamAnimation,d=dt.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},y=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},h=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{...dt.features,...e.features,...y!==void 0?{scrollToBottom:y}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??dt.suggestionChips,suggestionChipsConfig:{...dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...dt.layout,...e.layout,header:{...dt.layout?.header,...e.layout?.header},messages:{...dt.layout?.messages,...e.layout?.messages,avatar:{...dt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...dt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...dt.layout?.slots,...e.layout?.slots}},markdown:{...dt.markdown,...e.markdown,options:{...dt.markdown?.options,...e.markdown?.options}},messageActions:{...dt.messageActions,...e.messageActions}}:dt}var ri="16px",si="transparent",tc={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"}},nc={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"}},oc={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:ln,maxWidth:oi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ri,canvasBackground:si},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 ai(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 rc(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 Pu(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]=Pu(s,r):n[o]=r}return n}function sy(e,t){return t?Pu(e,t):e}function Ds(e,t={}){let n={palette:tc,semantic:nc,components:oc},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:sy(n.components,e?.components)};if(t.validate!==!1){let r=rc(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 ii(e){let t=ai(e),n={};for(let[w,q]of Object.entries(t)){let V=w.replace(/\./g,"-");n[`--persona-${V}`]=q.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"]??ri,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??si,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 y=d?.toggleGroup;y&&(y.gap&&(n["--persona-toggle-group-gap"]=y.gap),y.borderRadius&&(n["--persona-toggle-group-radius"]=y.borderRadius));let f=d?.artifact;if(f?.toolbar){let w=f.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(f?.tab){let w=f.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(f?.pane){let w=f.pane;if(w.toolbarBackground){let q=Gt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=q}}if(f?.card){let w=f.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(f?.inline){let w=f.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 h=d?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Gt(e,h.background)??h.background));let C=n["--persona-surface"],M=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",I=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",W=!M||M===C,$=W?P:M,N=W?I:M;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??N,W&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$,n}var Ru={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 ay={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"}}},Iu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Os=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",iy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Os()},li=e=>iy(e),ly=e=>Ds(e),cy=e=>Ds({...e,palette:{...e?.palette,colors:{...ay.colors,...e?.palette?.colors}}},{validate:!1}),Co=e=>{let t=li(e),n=Iu(e?.theme),o=Iu(e?.darkTheme);return t==="dark"?cy(Bs(n??{},o??{})):ly(n)},dy=e=>ii(e),nr=(e,t)=>{let n=Co(t),o=dy(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",li(t))},Dr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Os())});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(Os());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 Wn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Wu(e){let t=Wn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ci(e){if(typeof e!="string")return"";let t=e.indexOf(`
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 Ns(e){let t=Wu(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(Ns(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Wu(e.path);return t?t.toUpperCase():"File"}}}function Hu(e){let t=e.markdown??"";return e.file?{filename:Wn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:ci(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var sc="http://www.w3.org/2000/svg";function Bu(e){let t=document.createElementNS(sc,"svg");t.setAttribute("class",Un("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(sc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(sc,"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 Du(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 ac="persona-artifact-status-label",Ou="persona-artifact-status-detail",Nu="data-artifact-status-label",ic=new Map,Fu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Or(e){e&&ic.delete(e)}function py(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?wo(t):e.artifactType==="component"?"Component":"Document"}function Nr(e,t,n){let o=py(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=ic.get(a);e.status!=="complete"&&i===void 0&&(i=Fu(),ic.set(a,i));let p=i===void 0?0:Math.max(0,Fu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,y=d||c===""?0:c.split(`
29
+ `).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:y,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(h);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 uy(e){e.className=ac,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 or(e,t,n){let o=e.querySelector(`:scope > .${ac}`);o||(o=m("span",ac),e.appendChild(o)),o.getAttribute(Nu)!==t.label&&(uy(o),Du(o,t.label,n),o.setAttribute(Nu,t.label));let r=e.querySelector(`:scope > .${Ou}`),s=t.detail;s?(r||(r=m("span",Ou),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var fy={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"},gy=15e4,di={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 my(e,t){let n=(e||"").trim().toLowerCase();if(n&&di[n])return di[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(di[r])return di[r]}}return null}function pi(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 hy=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"]),yy=[{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=>hy.has(e)?"keyword":"plain"}];function _u(e){return pi(e,yy)}var by=[{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 vy(e){let t=pi(e,by);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 xy=[{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 $u(e){let t=pi(e,xy),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 Cy=[{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 wy(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 pi(p,Cy))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),y=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),f=y?r+y.index:o,h=e.slice(r,f),C=c==="script"?_u(h):$u(h);for(let M of C)t.push(M);r=f}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 Ay(e,t){switch(t){case"html":return wy(e);case"css":return $u(e);case"js":return _u(e);case"json":return vy(e)}}function Sy(e){let t=Wp(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=fy[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
+ `);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 ju(e,t,n){let o=e.length<=gy?my(t,n):null,r=o?Ay(e,o):[{type:"plain",value:e}];return Sy(r)}var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,So=zt+1;function To(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(So)):(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 f of t){if(f.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let M=ne(f.icon,16,"currentColor",1.5);M&&h.appendChild(M)}let C=document.createElement("span");C.textContent=f.label,h.appendChild(C),h.addEventListener("click",M=>{M.stopPropagation(),c(),n(f.id)}),a.appendChild(h)}let i=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!a.contains(h.target)&&!o.contains(h.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function y(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:y}}function gt(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 Gn(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 y=ne(t,s??14,"currentColor",2);y&&c.appendChild(y)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[y,f]of Object.entries(p))c.setAttribute(y,f);return c}function Jn(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=gt({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 ui(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 y=To({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(y.element),d.addEventListener("click",f=>{f.stopPropagation();let h=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),y.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),y.show()},close:()=>{d.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let f=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),d.remove()}}}var fi="persona-artifact-custom-action-btn";function Fr(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 "+fi+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+fi+(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=Gn({icon:e.icon,label:e.label,className:fi+(n?" persona-artifact-doc-copy-btn":"")}):o=gt({icon:e.icon,label:e.label,className:fi+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Fs(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 Uu(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?Wn(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 y=document.createElement("div");y.className="persona-truncate persona-text-sm persona-font-medium",y.style.color="var(--persona-text, #1f2937)",y.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let h=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}:{}},M=Nr(C,h,"card");or(f,M,h)}else s&&Or(s),f.textContent=p;if(u.append(y,f),d.append(c,u),a==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let M={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let P of h)try{if(P.visible===void 0||P.visible(M)){let I=Fr(P);I.setAttribute("data-artifact-custom-action",P.id),I.className=`${I.className} persona-flex-shrink-0`,d.append(I)}}catch{}}let C=Gn({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var gi=(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:()=>Uu(e,t)});if(i)return i}return Uu(e,t)};var Eo=new WeakMap;function lc(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=Eo.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Gu(e){return Eo.has(e)}function Ty(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 zu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Wn(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 Ey(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,My=240,ky=.8,Ly=300,Py=500,Ry="cubic-bezier(0.2, 0, 0, 1)",Vu=240,Iy=.35;function Wy(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(Py,Math.max(Ly,My+d*ky))),u=Math.round(c*Iy),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=y?y.animate([{opacity:0},{opacity:1}],{duration:Vu,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Ry});e.style.height=`${p}px`;let C=!1,M=()=>{C||(C=!0,i(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(c,u+Vu)+120)},qu)}function Hy(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 _s="--persona-artifact-inline-body-height";function By(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 y=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:y,completeDisplay:f}}function Ku(e,t){let n=Ty(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=Hy(o),p=o?.inlineActions??[],d=By(o),c=d.completeDisplay==="card",u=null,y=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=Z=>gi(Ey(Z),t),C=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(_s),f.replaceChildren(h(Z)),Eo.set(f,ce=>{f.replaceChildren(h(ce))})};if(c&&n.status==="complete")return C(n),f;let M=mi(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),P=m("div","persona-artifact-inline-body");P.appendChild(M.el);let I=Z=>{let ce=Z.status!=="complete",ee=ce?d.streamingHeight:d.completeHeight,we=typeof ee=="number";we?f.style.setProperty(_s,`${ee}px`):f.style.removeProperty(_s);let he=!!M.el.querySelector(".persona-code-pre"),ue=!!M.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");P.classList.toggle("persona-artifact-content-flush",he),P.classList.toggle("persona-artifact-inline-body--sized",we&&ue),P.classList.toggle("persona-artifact-inline-body--cap",!ce&&!ue&&typeof d.completeHeight=="number")},A=n.status,W=(Z,ce)=>{A!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(_s,`${d.completeHeight}px`):f.style.removeProperty(_s),Xu(P,ce?.suppressTransition?"none":d.transition,Z.id,()=>{M.update(Z),I(Z)})):M.update(Z),I(Z),A=Z.status};I(n);let $=d.overflow==="clip"&&a&&!!n.id;if($&&(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 ${zu(n).title} in panel`)),!r)return f.appendChild(P),Eo.set(f,W),f;let N=m("div","persona-artifact-inline-chrome");N.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),q=m("span","persona-flex persona-items-center persona-flex-shrink-0"),V=ne("file-text",16,"currentColor",2);V&&q.appendChild(V);let Y=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=m("span","persona-artifact-inline-type");w.append(q,Y,O);let U=m("div","persona-artifact-inline-chrome-actions"),me=m("span","persona-flex persona-items-center persona-gap-1"),ve=()=>u??d.viewMode,Me=i?Jn({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:ve(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let ce=Z==="source"?"source":"rendered";ce!==ve()&&(u=ce,M.update(y),I(y))}}):null,Oe=s?gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Oe&&n.id&&Oe.setAttribute("data-copy-artifact",n.id);let ie=a?gt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ie&&n.id&&ie.setAttribute("data-expand-artifact-inline",n.id),U.appendChild(me),Me&&U.appendChild(Me.element),Oe&&U.appendChild(Oe),ie&&U.appendChild(ie),N.append(w,U),f.append(N,P);let xe=Z=>{let{title:ce,typeLabel:ee}=zu(Z);Y.textContent=ce,Y.title=ce,$&&P.setAttribute("aria-label",`Open ${ce} in panel`);let we=Z.status!=="complete";if(we){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let he=Nr(Z,o,"inline-chrome");or(O,he,o)}else Or(Z.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=ee;if(Oe&&Oe.classList.toggle("persona-hidden",we),Me){let he=Z.artifactType==="markdown"?Z.file:void 0,ue=!1;if(!we&&he&&d.viewMode!=="source"){let Re=Ns(he);Re==="markdown"?ue=!0:(Re==="html"||Re==="svg")&&(ue=o?.filePreview?.enabled!==!1)}Me.element.classList.toggle("persona-hidden",!ue),Me.setSelected(ve())}if(me.replaceChildren(),!we&&p.length>0){let he=Fs(Z);if(he)for(let ue of p)try{if(ue.visible===void 0||ue.visible(he)){let Re=Fr(ue,{documentChrome:!0});Re.setAttribute("data-artifact-custom-action",ue.id),Re.classList.add("persona-flex-shrink-0"),me.appendChild(Re)}}catch{}}};return xe(n),Eo.set(f,(Z,ce)=>{if(c&&A!=="complete"&&Z.status==="complete"){let ee=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let we=Z,he=!1,ue=Re=>{we=Re,he=!0};Eo.set(f,ue),Wy(f,ee,{swap:()=>{C(we),he=!1,Eo.set(f,ue)},onSettled:()=>{he?C(we):Eo.set(f,Re=>{f.replaceChildren(h(Re))})}});return}(Z.status!=="complete"||Z.id!==y.id)&&(u=null),y=Z,W(Z,ce),xe(Z)}),f}var Ju=(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:()=>Ku(e,t)});if(i)return i}return Ku(e,t)};var cc=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)})}},En=new cc;En.register("PersonaArtifactCard",gi,{bubbleChrome:!1});En.register("PersonaArtifactInline",Ju,{bubbleChrome:!1});function $s(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ci(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var dc=!1;function Dy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Xu(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"||dc||s){o();return}dc=!0;let a=Dy(n);e.style.setProperty("view-transition-name",a);let i=()=>{dc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Oy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Ny="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Fy(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 _y(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 $y=220;function jy(){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 Uy(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(Bu());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 qy(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(A=>clearTimeout(A)),d.clear()},u=(A,W)=>{let $=setTimeout(()=>{d.delete($),A()},W);d.add($)},y=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let A=zy(r,s,o);a=A.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(y,$y))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):t.removeEventListener("load",I)},M=()=>{if(p||(p=!0,C(),c(),!a))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-i));A>0?u(h,A):h()};function P(A){if(n===null)return;let W=A.data;!W||W.persona!=="artifact-preview-ready"||W.token!==n||A.source===t.contentWindow&&M()}function I(){let A=W=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>W()):setTimeout(W,0)};A(()=>A(()=>M()))}return u(f,o.delayMs),u(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):t.addEventListener("load",I),()=>{p=!0,c(),C(),y()}}function mi(e,t){let{config:n}=t,o=t.registry??En,r=t.bodyLayout,s=n.markdown?Jo(n.markdown):null,a=Tr(n.sanitize),i=e,p=!1,d=ie=>{let xe=jn()!==null;s&&!xe&&!p&&(p=!0,Sr(()=>Oe(i)));let Z=s?s(ie):Rn(ie);return s&&xe&&a?a(Z):Z},c=m("div","persona-artifact-preview-body"),u=null,y=null,f=null,h=()=>{f&&(f(),f=null),u=null,y=null},C=null,M=null,P=null,I=!1,A=()=>{C=null,M=null,P=null,I=!1},W=null,$=null,N=()=>{W=null,$=null},w=40,q=0,V=ie=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ie()):setTimeout(ie,0),Y=ie=>ie.scrollHeight-ie.clientHeight-ie.scrollTop<=w,O=ie=>{if(!r)return;let xe=ie.scrollHeight-ie.clientHeight>1,Z=ie.scrollHeight-ie.clientHeight-ie.scrollTop;ie.classList.toggle("persona-artifact-fade-top",r.fadeTop&&xe&&ie.scrollTop>1),ie.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&xe&&Z>1)},U=ie=>{q||(q=V(()=>{q=0,ie.scrollTop=ie.scrollHeight,O(ie)}))},me=(ie,xe,Z,ce)=>{let ee=!!r,we=Z.id+"|"+(ee?"w":"p");if(!C||P!==we||C.parentElement!==c){h(),N(),c.replaceChildren();let Re=m("pre",Oy+" persona-code-pre"),Ne=m("code","persona-code");if(Re.appendChild(Ne),ee){let je=m("div","persona-artifact-source-window");if(je.appendChild(Re),c.appendChild(je),!(r?.overflow==="clip")&&typeof je.addEventListener=="function"){let Ue=()=>je.scrollHeight-je.clientHeight>1;je.addEventListener("scroll",()=>{Y(je)&&(I=!1),O(je)},{passive:!0}),je.addEventListener("wheel",Xe=>{Ue()&&Xe.deltaY<0&&(I=!0)},{passive:!0}),je.addEventListener("touchmove",()=>{Ue()&&(I=!0)},{passive:!0})}C=je}else c.appendChild(Re),C=Re;M=Ne,P=we}let he=ee?C:null;he&&(he.classList.toggle("persona-artifact-source-window--fixed",ce),he.classList.toggle("persona-artifact-source-window--clip",ce&&r?.overflow==="clip"));let ue=he?Y(he):!0;if(M.replaceChildren(ju(ie,xe?.language,xe?.path)),he){let Re=Z.status!=="complete";ce&&Re&&r?.followOutput&&!I&&ue?U(he):Re||(I=!1),O(he)}},ve=ie=>{h(),A(),N(),c.replaceChildren();let xe=m("div",Ny);xe.innerHTML=d(ie),c.appendChild(xe)},Me=ie=>{let xe=ie.id,Z=n.features?.artifacts,ce=Nr(ie,Z,"status-body");if(W&&$===xe&&W.parentElement===c){let he=W.querySelector(".persona-artifact-status-view-text");he&&or(he,ce,Z);return}h(),A(),c.replaceChildren();let ee=m("div","persona-artifact-status-view"),we=m("div","persona-artifact-status-view-text");or(we,ce,Z),ee.appendChild(we),c.appendChild(ee),W=ee,$=xe},Oe=ie=>{i=ie;let xe=t.resolveViewMode?.(ie)??r?.viewMode??"rendered",Z=ie.artifactType==="markdown"?ie.file:void 0,ce=ie.status!=="complete";ce||Or(ie.id);let ee=ce?r?.streamingHeight:r?.completeHeight,we=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&ce){Me(ie);return}if(Z){let ue=ci(ie.markdown??""),Re=Ns(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&xe==="rendered"&&Ne&&(Re==="html"||Re==="svg")){let Be=ie.id+"\0"+ue;if(u&&y===Be&&u.parentElement===c)return;A(),N(),h(),c.replaceChildren();let Ue=n.features?.artifacts?.filePreview,Xe=Ue?.iframeSandbox??"allow-scripts";!Ue?.dangerouslyAllowSameOrigin&&Xe.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."),Xe=Xe.split(/\s+/).filter(yt=>yt&&yt!=="allow-same-origin").join(" "));let ke=_y(Ue?.loading),oe=m("div","persona-artifact-frame"),Ie=m("iframe","persona-artifact-iframe");Ie.setAttribute("sandbox",Xe),Ie.setAttribute("data-artifact-id",ie.id);let Ct=null;ke.enabled&&ke.injectReadySignal?(Ct=jy(),Ie.srcdoc=ue+Uy(Ct)):Ie.srcdoc=ue,oe.appendChild(Ie),c.appendChild(oe),ke.enabled&&(f=qy(oe,Ie,Ct,ke,ie.id,n)),u=oe,y=Be;return}if(h(),!ce&&Re==="markdown"&&xe==="rendered"){ve(ue);return}me(ue,{language:Z.language,path:Z.path},ie,we);return}if(ie.artifactType==="markdown"){if(xe==="source"){h(),me(ie.markdown??"",void 0,ie,we);return}ve(ie.markdown??"");return}h(),A(),N(),c.replaceChildren();let he=ie.component?o.get(ie.component):void 0;if(he){let Re={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=he(ie.props??{},Re);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(Fy(ie))};return Oe(e),{el:c,update(ie){Oe(ie)}}}var Qu=require("idiomorph"),hi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Qu.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 Yu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var pc={index:-1,draft:""};function Zu(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 ef(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 tf(){return new Map}function nf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function of(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function rf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function yi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Hn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Mo(e,t){return Hn(e)-e.scrollTop<=t}function bi(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 vi(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 sf(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function af(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 lf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var js={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Vy=["pre","code","a","script","style"],xi=e=>({type:e?.type??js.type,placeholder:e?.placeholder??js.placeholder,speed:e?.speed??js.speed,duration:e?.duration??js.duration,buffer:e?.buffer??js.buffer}),df=[{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"}],Us=new Map;for(let e of df)Us.set(e.name,e);var pf=e=>{Us.set(e.name,e)},uf=e=>{df.some(t=>t.name===e)||Us.delete(e)},ff=()=>Array.from(Us.keys()),_r=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Us.get(e)??null,Ci=(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},Ky=(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},Gy=(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},uc=/\s/,Jy=(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},Xy=(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(uc.test(s[i])){let p=i;for(;p<s.length&&uc.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&&!uc.test(s[d]);)p.appendChild(Ky(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},Qy=(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(Gy(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},zs=(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??Vy).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)Jy(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Xy:Qy;for(let u of i)c(u,n,d);return r.innerHTML},wi=(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},qs=(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},cf=new WeakMap,Yy=(e,t)=>{if(!e.styles)return;let n=cf.get(t);if(n||(n=new Set,cf.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,Zy=(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)},gf=e=>{let t=fc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ai=(e,t)=>{Yy(e,t),Zy(e,t)};function gc(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 Vs=0,ko=null;function mc(e=document){if(Vs++,Vs===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ko={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,Vs=Math.max(0,Vs-1),Vs===0&&ko)){let n=e.body,o=e.defaultView??window;n.style.overflow=ko.originalOverflow,n.style.position=ko.originalPosition,n.style.top=ko.originalTop,n.style.width=ko.originalWidth,o.scrollTo(0,ko.scrollY),ko=null}}}var Ks={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},It=e=>(e?.launcher?.mountMode??"floating")==="docked",Lo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",en=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ks.side,width:t?.width??Ks.width,animate:t?.animate??Ks.animate,reveal:t?.reveal??Ks.reveal,maxHeight:t?.maxHeight??Ks.maxHeight}};var Mn={"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 eb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=eb,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",y=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),h=Fe("button",{className:Un("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ne(u,s,"currentColor",1);if(C?(C.style.display="block",h.appendChild(C)):h.textContent=y,p.appendChild(h),c&&d){let M=null,P=()=>{if(M)return;let A=h.ownerDocument,W=A.body;if(!W)return;M=In(A,"div","persona-clear-chat-tooltip"),M.textContent=d;let $=In(A,"div");$.className="persona-clear-chat-tooltip-arrow",M.appendChild($);let N=h.getBoundingClientRect();M.style.position="fixed",M.style.zIndex=String(So),M.style.left=`${N.left+N.width/2}px`,M.style.top=`${N.top-8}px`,M.style.transform="translate(-50%, -100%)",W.appendChild(M)},I=()=>{M&&M.parentNode&&(M.parentNode.removeChild(M),M=null)};p.addEventListener("mouseenter",P),p.addEventListener("mouseleave",I),h.addEventListener("focus",P),h.addEventListener("blur",I),p._cleanupTooltip=()=>{I(),p.removeEventListener("mouseenter",P),p.removeEventListener("mouseleave",I),h.removeEventListener("focus",P),h.removeEventListener("blur",I)}}return{button:h,wrapper:p}},tb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ti=(e,t={})=>{let{wrapperClassName:n=tb,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??"",y=a.borderColor??"",f=a.borderRadius??"",h=a.paddingX??"",C=a.paddingY??"",M=a.tooltipText??"Clear chat",P=a.showTooltip??!0,I=m("div",n),A=!!(u||y),W=Fe("button",{className:Un("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:A?`${u||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),$=ne(p,r,"currentColor",1);if($&&($.style.display="block",W.appendChild($)),I.appendChild(W),P&&M){let N=null,w=()=>{if(N)return;let V=W.ownerDocument,Y=V.body;if(!Y)return;N=In(V,"div","persona-clear-chat-tooltip"),N.textContent=M;let O=In(V,"div");O.className="persona-clear-chat-tooltip-arrow",N.appendChild(O);let U=W.getBoundingClientRect();N.style.position="fixed",N.style.zIndex=String(So),N.style.left=`${U.left+U.width/2}px`,N.style.top=`${U.top-8}px`,N.style.transform="translate(-50%, -100%)",Y.appendChild(N)},q=()=>{N&&N.parentNode&&(N.parentNode.removeChild(N),N=null)};I.addEventListener("mouseenter",w),I.addEventListener("mouseleave",q),W.addEventListener("focus",w),W.addEventListener("blur",q),I._cleanupTooltip=()=>{q(),I.removeEventListener("mouseenter",w),I.removeEventListener("mouseleave",q),W.removeEventListener("focus",w),W.removeEventListener("blur",q)}}return{button:W,wrapper:I}};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))"},Xn=e=>{let{config:t,showClose:n=!0}=e,o=Fe("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=Fe("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 $=parseFloat(s)||24,N=ne(p,$*.6,"currentColor",1);N?d.replaceChildren(N):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let $=m("img");$.src=t.launcher.iconUrl,$.alt="",$.className="persona-rounded-xl persona-object-cover",$.style.height=s,$.style.width=s,d.replaceChildren($)}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=Fe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),y=Fe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});c.append(u,y),i?o.append(c):o.append(d,c);let f=r.clearChat??{},h=f.enabled??!0,C=f.placement??"inline",M=null,P=null;if(h){let N=Ti(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=N.button,P=N.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&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:A,wrapper:W}=Si(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(W),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:y,closeButton:A,closeButtonWrapper:W,clearChatButton:M,clearChatButtonWrapper:P}},rr=(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 hc=e=>{let t=Xn({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 nb(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=To({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 yc=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=ui({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),nb(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let A=r.onTitleClick;d.addEventListener("click",W=>{W.target.closest("button")||A()}),d.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),A())})}let I=r?.titleRowHover;I&&(d.style.borderRadius=I.borderRadius??"10px",d.style.padding=I.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=I.background??"",d.style.borderColor=I.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",y=m("div",""),f=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");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Jt.actionIconColor;let h=a.closeButtonIconName??"x",C=ne(h,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),y.appendChild(f),i.appendChild(y);let M=m("div");M.style.display="none";let P=m("span");return P.style.display="none",{header:i,iconHolder:M,headerTitle:c,headerSubtitle:P,closeButton:f,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},Ei={default:hc,minimal:yc},bc=e=>Ei[e]??Ei.default,$r=(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=bc(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 Mi=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}},ki=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",y=t.backgroundColor,f=t.textColor,h=m("div","persona-send-button-wrapper"),C=Fe("button",{className:Un("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&&!y&&"persona-bg-persona-primary",!n&&!f&&"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?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&y||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}}),M=null,P=null;if(n){let $=parseFloat(u)||24,N=f?.trim()||"currentColor";r?(M=ne(r,$,N,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,P=ne(s,$,N,2)}else C.textContent=p;let I=null;c&&a&&(I=m("div","persona-send-button-tooltip"),I.textContent=a,h.appendChild(I)),C.setAttribute("aria-label",a),h.appendChild(C);let A="send";return{button:C,wrapper:h,setMode:$=>{if($===A)return;A=$;let N=$==="stop"?i:a;if(C.setAttribute("aria-label",N),I&&(I.textContent=N),n){if(M&&P){let w=$==="stop"?P:M;C.replaceChildren(w)}}else C.textContent=$==="stop"?d:p}}},Li=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,y=m("div","persona-send-button-wrapper"),f=Fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width: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?f.appendChild(C):f.textContent="\u{1F3A4}",y.appendChild(f);let M=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&M){let I=m("div","persona-send-button-tooltip");I.textContent=M,y.appendChild(I)}return{button:f,wrapper:y}},Pi=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??Kn).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=Fe("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",h=>{h.preventDefault(),r.click()}),d.appendChild(c);let y=t.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=y,d.appendChild(f),{button:c,wrapper:d,input:r,previewsContainer:o}},Ri=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},Ii=()=>Fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var jr=e=>{let{config:t}=e,n=Fe("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=Ii(),r=Fe("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}=Mi(t);a();let i=ki(t),p=Li(t),d=Pi(t),c=Ri(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Fe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&y.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),u.append(y,f),r.append(u),r.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.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:y,rightActions:f,setSendButtonMode:i.setMode}};var mf=()=>{let e=Fe("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}},hf=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ii(),r=Ri(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Mi(t);s.style.maxHeight="100px",a();let i=ki(t),p=Li(t),d=Pi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Fe("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 y=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&y.append(p.wrapper),y.append(i.wrapper),c.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,y),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=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:f,leftActions:u,rightActions:y,setSendButtonMode:i.setMode}};var yf=e=>{let t=e?.launcher?.enabled??!0,n=It(e);if(Lo(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 y=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",u.appendChild(y);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??zt),{wrapper:u,panel:y,pillRoot:f}}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"),y=e?.launcher?.width??"100%";return c.style.width=y,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Mn[r.position]?Mn[r.position]:Mn["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??ln;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},ob=(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}=Si(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 W=Ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=W.button,i=W.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=Fe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Fe("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=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),y=Fe("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),f=m("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(y.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(y,f);let M=Fe("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=hf({config:e}),{root:I,textNode:A}=mf();return n.append(p,r,d,M),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:f,composerOverlay:M,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:I,peekTextNode:A}},bf=(e,t=!0)=>{if(Lo(e))return ob(e,t);let n=Fe("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?$r(e,o,{showClose:t}):Xn({config:e,showClose:t}),a=Fe("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=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:It(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 f=jr({config:e}),h=e?.layout?.showFooter!==!1;r?rr(n,s,e):(s.header.style.display="none",rr(n,s,e)),n.append(a);let C=Fe("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 h||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle: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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var vc=(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 Ws=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=r=>{let a=r.launcher??{},i=Wt(r),p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let A=a.subtitle??"Here to help you get answers fast";d.textContent=A,d.setAttribute("title",A)}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 A=a.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,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 W=parseFloat(A)||24,$=oe(a.agentIconName,W*.6,"var(--persona-text-inverse, #ffffff)",2);$?(u.appendChild($),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 y=n.querySelector("[data-role='launcher-image']");if(y){let A=a.agentIconSize??"40px";y.style.height=A,y.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=a.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let W=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,W=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let $=parseFloat(A)||24,N=Math.max($-W,8),w=oe(a.callToActionIconName,N,"currentColor",2);w?f.appendChild(w):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let h=a.position&&Mn[a.position]?Mn[a.position]:Mn["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",M="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?M:`${C} ${h}`,i||(n.style.zIndex=String(a.zIndex??zt));let P="1px solid var(--persona-border, #e5e7eb)",I="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:I,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="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:s}};var bf=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:s}=hf(e),r=yf(e,t),a={wrapper:n,panel:o,pillRoot:s},i={container:r.container,body:r.body,messagesWrapper:r.messagesWrapper,composerOverlay:r.composerOverlay,introTitle:r.introTitle,introSubtitle:r.introSubtitle},p={element:r.header,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper},d={footer:r.footer,form:r.composerForm,textarea:r.textarea,sendButton:r.sendButton,sendButtonWrapper:r.sendButtonWrapper,micButton:r.micButton,micButtonWrapper:r.micButtonWrapper,statusText:r.statusText,suggestions:r.suggestions,attachmentButton:r.attachmentButton,attachmentButtonWrapper:r.attachmentButtonWrapper,attachmentInput:r.attachmentInput,attachmentPreviewsContainer:r.attachmentPreviewsContainer,actionsRow:r.actionsRow,leftActions:r.leftActions,rightActions:r.rightActions,setSendButtonMode:r.setSendButtonMode,peekBanner:r.peekBanner,peekTextNode:r.peekTextNode};return{shell:a,panelElements:r,transcript:i,header:p,composer:d,replaceHeader:y=>(p.element.replaceWith(y.header),p.element=y.header,p.iconHolder=y.iconHolder,p.headerTitle=y.headerTitle,p.headerSubtitle=y.headerSubtitle,p.closeButton=y.closeButton,p.closeButtonWrapper=y.closeButtonWrapper,p.clearChatButton=y.clearChatButton,p.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{d.footer.replaceWith(y),d.footer=y}}},vc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(r=>r.renderLauncher);if(o?.renderLauncher){let r=o.renderLauncher({config:e,defaultRenderer:()=>bc(e,n).element,onToggle:n});if(r)return{instance:null,element:r}}let s=bc(e,n);return{instance:s,element:s.element}};var tb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},nb=(e,t)=>{if(!e)return null;let n=tb(e);if(n===null)return null;let o=t?.[e],s=o!==void 0?o:n;return s||null},ob=(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},rb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},xc=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(":"))},Cc=320,wf=320,sb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ab=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),lb=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}}),s=m("span","persona-mention-chip-icon"),r=oe(n.iconName??"at-sign",13,"currentColor",2);r&&s.appendChild(r),o.appendChild(s),o.appendChild($e("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},db=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Hs(o.ref,{readonly:!0,render:t}))}return n},vf="\uE000",xf="\uE001",pb=(e,t,n,o)=>{let s=Math.random().toString(36).slice(2,8),r=y=>`${vf}${s}:${y}${xf}`,a=t.map((y,f)=>y.kind==="text"?y.text:r(f)).join(""),i=n(a);if(!t.every((y,f)=>y.kind==="text"||i.includes(r(f)))){e.replaceChildren(db(t,o));return}e.innerHTML=i;let d=new RegExp(`${vf}${s}:(\\d+)${xf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let y=c.nextNode();y;y=c.nextNode())u.push(y);for(let y of u){let f=y;for(let h=d.exec(f.data);h;h=d.exec(f.data)){let C=t[Number(h[1])],M=f.splitText(h.index);M.data=M.data.slice(h[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(Hs(C.ref,{readonly:!0,render:o}),M),f=M}}},ub=(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 s=0,r=!1,a=()=>{r||(r=!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=`${Cc}px`,d.style.maxHeight=`${wf}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;s+=1,d.addEventListener("error",()=>{c||(c=!0,s=Math.max(0,s-1),d.remove(),s===0&&a())}),d.addEventListener("load",()=>{c=!0}),rb(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,s=Math.max(0,s-1),d.remove())}),s===0?(a(),null):o}catch{return n?.(),null}},fb=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(!xc(o.audio))return;let s=m("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Cc}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},gb=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(!xc(o.video))return;let s=m("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Cc}px`,s.style.maxHeight=`${wf}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},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(!xc(o.data))return;let s=m("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},sr=()=>{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 s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(s),e},wc=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:sr};if(t){let s=t(o);if(s!==null)return s}return sr()},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 s=m("img");s.src=o,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=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},Cf=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?o.textContent=t.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},yb=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Ac=(e,t,n)=>{let o=t.showCopy??!0,s=t.showUpvote??!0,r=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!s&&!r&&!a){let h=m("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}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],y=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let f=(h,C,M)=>{let P=mt({icon:h,label:C,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",M),P};return o&&y.appendChild(f("copy","Copy message","copy")),a&&y.appendChild(f("volume-2","Read aloud","read-aloud")),s&&y.appendChild(f("thumbs-up","Upvote","upvote")),r&&y.appendChild(f("thumbs-down","Downvote","downvote")),y},Ur=(e,t,n,o,s,r)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,y=p?.position??"left",f=d?.position??"below",h=yb(e.role,i),C=m("div",h.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=sb(e),P=e.content?.trim()??"",A=M.length>0&&P===Ja,W=xi(r?.widgetConfig?.features?.streamAnimation),$=r?.widgetConfig?.features?.streamAnimation?.plugins,N=e.role==="assistant"&&W.type!=="none"?_r(W.type,$):null,w=e.role==="assistant"&&N?.isAnimating?.(e)===!0,z=e.role==="assistant"&&N!==null&&(!!e.streaming||w);z&&N?.bubbleClass&&C.classList.add(N.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),z&&N&&(N.containerClass&&V.classList.add(N.containerClass),V.style.setProperty("--persona-stream-step",`${W.speed}ms`),V.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let Y=z?Ci(e.content??"",W.buffer,N,e,!!e.streaming):e.content??"",O=()=>{let ee=t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&N?.wrap==="char"?Us(ee,"char",e.id,{skipTags:N.skipTags}):z&&N?.wrap==="word"?Us(ee,"word",e.id,{skipTags:N.skipTags}):ee},U=null;if(A?(U=document.createElement("div"),U.innerHTML=O(),U.style.display="none",V.appendChild(U)):e.contentSegments?.length?pb(V,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),r?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=O(),z&&N?.useCaret&&!A&&P){let ee=wi(),Ce=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),he=Ce[Ce.length-1];if(he?.parentNode)he.parentNode.insertBefore(ee,he.nextSibling);else{let fe=V.lastElementChild;fe?fe.appendChild(ee):V.appendChild(ee)}}if(u&&f==="inline"&&e.createdAt){let ee=Cf(e,d,"span");ee.classList.add("persona-timestamp-inline");let Ce=V.lastElementChild;Ce?Ce.appendChild(ee):V.appendChild(ee)}if(M.length>0){let ee=ub(M,!A&&!!P,()=>{A&&U&&(U.style.display="")});ee?C.appendChild(ee):A&&U&&(U.style.display="")}let me=ab(e);if(me.length>0){let ee=fb(me);ee&&C.appendChild(ee)}let be=ib(e);if(be.length>0){let ee=gb(be);ee&&C.appendChild(ee)}let Me=lb(e);if(Me.length>0){let ee=mb(Me);ee&&C.appendChild(ee)}let Oe=e.contentSegments?.length?null:cb(e.contextMentions);if(Oe&&C.appendChild(Oe),C.appendChild(V),u&&f==="below"&&e.createdAt){let ee=Cf(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let ae=e.role==="assistant"?nb(e.stopReason,r?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(Y&&Y.trim()),Ce=W.placeholder==="skeleton",he=Ce&&W.buffer==="line"&&ee;if(ee)he&&C.appendChild(zs());else if(Ce)C.appendChild(zs());else{let fe=wc("inline",r?.loadingIndicatorRenderer,r?.widgetConfig);fe&&C.appendChild(fe)}}if(ae&&e.stopReason&&!e.streaming&&(P||(V.style.display="none"),C.appendChild(ob(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Ac(e,o,s);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=m("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=hb(p,e.role);return y==="right"||y==="left"&&e.role==="user"?Z.append(C,de):Z.append(de,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Z},Af=(e,t,n,o,s,r)=>{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}):Ur(e,t,n,o,s,r)};var zr=new Set,bb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),vb=(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
- `):""},Sf=(e,t)=>{let n=zr.has(e),o=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),r=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!s)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=oe(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",r&&(r.style.display=n?"none":r.textContent||r.childNodes.length?"":"none")},Sc=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let s=t?.features?.reasoningDisplay??{},r=s.expandable!==!1,a=r&&zr.has(e.id),i=n.status!=="complete",p=vb(e,s.previewMaxLines??3),d=m("button",r?"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",r&&(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"),y="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),C=()=>{let be=m("span","");return be.setAttribute("data-tool-elapsed",h),be.textContent=ja(n),be},M=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:p,isActive:i,config:t??{},elapsed:ja(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,c.appendChild(u)):M instanceof HTMLElement?c.appendChild(M):(u.textContent=y,c.appendChild(u));let P=m("span","persona-text-xs persona-text-persona-primary");P.textContent=Kp(n),c.appendChild(P);let I=s.loadingAnimation??"none",A=f.activeTextTemplate,W=f.completeTextTemplate,$=i?A:W,N=M instanceof HTMLElement,w=(be,Me)=>{u.textContent="";let Oe=Ua(be,""),ae=0;for(let ve of Oe){let Z=ve.styles.length>0?(()=>{let de=m("span",ve.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(de),de})():u;if(ve.isDuration&&i)Z.appendChild(C());else{let de=ve.isDuration?ja(n):ve.text;Me?ae=Ao(Z,de,ae):Z.appendChild(document.createTextNode(de))}}};if(!N&&$)if(P.style.display="none",u.style.display="",i&&I!=="none"){let be=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`),w($,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`),I==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w($,!0))}else w($,!1);else if(!N&&i&&I!=="none"){u.style.display="";let be=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`),I==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Me=u.textContent||y;u.textContent="",Ao(u,Me,0)}n.status==="complete"&&(u.style.display="none")}else N||(n.status==="complete"?u.style.display="none":u.style.display="");let z=null;if(r){z=m("div","persona-flex persona-items-center");let Me=oe(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?z.appendChild(Me):z.textContent=a?"Hide":"Show";let Oe=m("div","persona-flex persona-items-center persona-ml-auto");Oe.append(z),d.append(c,Oe)}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&&s.activePreview&&p){let be=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});bb(V,be)||(V.textContent=p),V.style.display=""}if(!a&&i&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!r)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 O=n.chunks.join(""),U=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return U.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Y.appendChild(U),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Me=oe(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?z.appendChild(Me):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 qr=new Set,xb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Cb=(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
- `);let s=ho(n.args).trim();return s?s.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).slice(0,t).join(`
44
- `):""},Tc=(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)"},wb=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",r=Cb(e,o?.previewMaxLines??3),a=n?Gp(n):"";if(!n)return{summary:a,previewText:r,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return s==="tool-name"?d=n.name?.trim()||a:s==="tool-preview"&&r&&(d=r),i&&p.activeTextTemplate?d=Kl(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=Kl(n,p.completeTextTemplate,d)),{summary:d,previewText:r,isActive:i}},Tf=(e,t,n)=>{let o=qr.has(e),s=n?.toolCall??{},r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!r||!a)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",u=oe(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")},Ec=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},s=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),o.backgroundColor&&(s.style.backgroundColor=o.backgroundColor),o.borderColor&&(s.style.borderColor=o.borderColor),o.borderWidth&&(s.style.borderWidth=o.borderWidth),o.borderRadius&&(s.style.borderRadius=o.borderRadius),s.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 s;let r=t?.features?.toolCallDisplay??{},a=r.expandable!==!1,i=a&&qr.has(e.id),{summary:p,previewText:d,isActive:c}=wb(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 y=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),C=()=>{let O=m("span","");return O.setAttribute("data-tool-elapsed",h),O.textContent=Ls(n),O},M=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:r.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ls(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(f.textContent=M,y.appendChild(f)):M instanceof HTMLElement?y.appendChild(M):(f.textContent=p,y.appendChild(f));let P=r.loadingAnimation??"none",I=o.activeTextTemplate,A=o.completeTextTemplate,W=c?I:A,$=M instanceof HTMLElement,N=(O,U)=>{f.textContent="";let me=n.name?.trim()||"tool",be=Ua(O,me),Me=0;for(let Oe of be){let ae=Oe.styles.length>0?(()=>{let ve=m("span",Oe.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(ve),ve})():f;if(Oe.isDuration&&c)ae.appendChild(C());else{let ve=Oe.isDuration?Ls(n):Oe.text;U?Me=Ao(ae,ve,Me):ae.appendChild(document.createTextNode(ve))}}};if(!$)if(c&&P!=="none"){let O=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),P==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),W&&N(W,!1);else if(f.classList.add(`persona-tool-loading-${P}`),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),W)N(W,!0);else{let U=f.textContent||p;f.textContent="",Ao(f,U,0)}}else W&&N(W,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=oe(i?"chevron-up":"chevron-down",16,O,2);U?w.appendChild(U):w.textContent=i?"Hide":"Show";let me=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");me.append(w),u.append(y,me)}else u.append(y);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&&r.activePreview&&d){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});xb(z,O)||(z.textContent=d),z.style.display=""}if(!i&&c&&r.activeMinHeight&&(s.style.minHeight=r.activeMinHeight),!a)return s.append(u,z),s;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 O=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,V.appendChild(O)}if(n.args!==void 0){let O=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let me=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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",Tc(me,o),me.textContent=ho(n.args),O.append(U,me),V.appendChild(O)}if(n.chunks&&n.chunks.length){let O=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let me=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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",Tc(me,o),me.textContent=n.chunks.join(""),O.append(U,me),V.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let me=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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",Tc(me,o),me.textContent=ho(n.result),O.append(U,me),V.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,V.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=oe(i?"chevron-up":"chevron-down",16,O,2);U?w.appendChild(U):w.textContent=i?"Hide":"Show"}V.style.display=i?"":"none",z.style.display=i?"none":z.textContent||z.childNodes.length?"":"none"})(),s.append(u,z,V),s};var ar=new Map,Wi=e=>{let n=(e.startsWith(Sn)?e.slice(Sn.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)},Ef=e=>e?.approval!==!1?e?.approval:void 0,Mf=(e,t)=>{let n=Ef(t)?.detailsDisplay??"collapsed";return ar.get(e)??n==="expanded"},kf=(e,t,n)=>{let o=Ef(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let r=e.querySelector("[data-approval-details-chevron]");if(r){r.innerHTML="";let a=oe(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&r.appendChild(a)}},Lf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!o||!s)return;let r=Mf(e,n);kf(o,r,n),s.style.display=r?"":"none"};var Hi=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,s=n?.status==="pending",r=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",r.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",r.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 r;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=oe(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),y=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",y.appendChild(f),!s){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"),y.appendChild(w)}u.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(Sn)?As(n.toolName):void 0,M=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,I=M||(P?n.description:`The assistant wants to use \u201C${C??Wi(n.toolName)}\u201D.`),A=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=I,u.appendChild(A),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 W=o?.detailsDisplay??"collapsed",$=!!n.description&&!P,N=$||!!n.parameters;if(W!=="hidden"&&N){let w=Mf(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),kf(z,w,t),u.appendChild(z);let O=m("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",$){let U=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,O.appendChild(U)}if(n.parameters){let U=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&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=ho(n.parameters),O.appendChild(U)}u.appendChild(O)}if(s){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=oe("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 O=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");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let U=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",O.appendChild(U));let me=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(me),w.append(z,O),u.appendChild(w)}return a.append(i,u),r.appendChild(a),r};function Ab(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Pf(e){let{anchor:t,content:n,placement:o="bottom-start",offset:s=6,matchAnchorWidth:r=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??Ab(t),y=!1,f=null,h=()=>{if(!y)return;let P=t.getBoundingClientRect();n.style.position="fixed",r&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let I=n.getBoundingClientRect(),A=i?.()??null,W=A!=null?P.top+A:P.top,$=o==="top-start"||o==="top-end"?W-s-I.height:P.bottom+s,w=o==="bottom-end"||o==="top-end"?P.right-I.width:P.left,z=a?.()??null;if(z!=null){let V=Math.max(P.left,P.right-I.width);w=Math.min(Math.max(P.left+z,P.left),V)}n.style.top=`${$}px`,n.style.left=`${w}px`},C=()=>{y&&(y=!1,f&&(f(),f=null),n.remove())},M=()=>{if(y)return;y=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let P=(t.ownerDocument??document).defaultView??window,I=t.ownerDocument??document,A=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}h()},W=N=>{let w=typeof N.composedPath=="function"?N.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},$=P.setTimeout(()=>{I.addEventListener("pointerdown",W,!0)},0);P.addEventListener("scroll",A,!0),P.addEventListener("resize",A),f=()=>{P.clearTimeout($),I.removeEventListener("pointerdown",W,!0),P.removeEventListener("scroll",A,!0),P.removeEventListener("resize",A)},d?.()};return{get isOpen(){return y},open:M,close:C,toggle:()=>y?C():M(),reposition:h,destroy:C}}function Rf(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Sb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),If=(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))},ir=(e,t)=>{If(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)},Tb=e=>e?.approval!==!1?e?.approval:void 0,Eb=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return ar.get(e)??n==="expanded"},Mc=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Mb=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let s=e.toolType==="webmcp"||e.toolName.startsWith(Sn)?As(e.toolName):void 0,r=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...s?{displayTitle:s}:{},...e.reason?{reason:e.reason}:{}});if(r)return n.textContent=r,n;let a=s??Wi(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},kb=e=>{let t=m("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?Wi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Lb=(e,t,n,o,s,r,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,y=u&&Eb(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?h:f)):C.setAttribute("data-static","true");let M=m("span","persona-approval-logo"),P=oe("shield-check",16,"currentColor",2);P&&M.appendChild(P),C.appendChild(M);let I=Mb(n,o);if(u){let z=m("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let V=oe("chevron-down",14,"currentColor",2);V&&z.appendChild(V),I.append(" "),I.appendChild(z)}C.appendChild(I),i.appendChild(C);let A=m("div","persona-approval-body");if(u){let z=m("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!y,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)}A.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)),A.appendChild(z)}let W=m("div","persona-approval-actions"),$=null,N=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"),N(V),V.append(o?.approveLabel??"Always allow",Mc("\u23CE"));let Y=m("button","persona-approval-caret");Y.type="button",Y.setAttribute("data-action","toggle-menu"),Y.setAttribute("aria-label","More options"),N(Y);let O=oe("chevron-down",15,"currentColor",2);O&&Y.appendChild(O),z.append(V,Y),W.append(z,w),w.append(Mc("Esc"));let U=m("div","persona-approval-menu"),me=m("button","persona-approval-menu-item");me.type="button",me.append("Allow once",Mc("\u2318\u23CE")),U.appendChild(me),$=Pf({anchor:z,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,$),me.addEventListener("click",()=>{ir(e,t.id),s()})}else{let z=m("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),N(z),z.append(o?.approveLabel??"Allow"),W.append(z,w)}return A.appendChild(W),i.appendChild(A),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 O=i.querySelector('[data-role="params"]');if(O){let U=O.hidden;O.hidden=!U,C.setAttribute("aria-expanded",U?"true":"false"),C.setAttribute("aria-label",U?h:f),ar.set(t.id,U)}return}if(Y==="toggle-menu"){$?.toggle();return}if(Y==="always"){ir(e,t.id),s({remember:!0});return}if(Y==="allow"){ir(e,t.id),s();return}if(Y==="deny"){ir(e,t.id),r();return}}),i},Wf=()=>{let e=Sb();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:s,deny:r,config:a})=>{let i=o?.approval;if(!i)return null;let p=Tb(a);if(i.status!=="pending"){if(ir(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return kb(i)}If(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Lb(e,o,i,p,s,r,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=y=>{Rf(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),ir(e,o.id),y.key==="Escape"?r():y.metaKey||y.ctrlKey?s():s({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()])ir(e,o);e.latestPendingApprovalId=null}}};var Hf=e=>{let t=[],n=null;return{buttons:t,render:(s,r,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!s||!s.length||!c&&(i??(r?r.getMessages():[])).some(M=>M.role==="user"))return;let u=document.createDocumentFragment(),y=r?r.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(s.forEach(h=>{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=h,C.disabled=y,p?.fontFamily&&(C.style.fontFamily=f(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",()=>{!r||r.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),r.sendMessage(h))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let h=JSON.stringify(s);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var Ks=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 Gs=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 s=o.result;s.objectStoreNames.contains(this.storeName)||s.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 s of t)o.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let r=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();r.onsuccess=()=>{t()},r.onerror=()=>{n(r.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 s of t)o.put(s)}catch{}}};var Pb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Rb=new Set(["step_start","execution_start"]),Ib=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Wb=new Set(["step_complete","agent_turn_complete"]),Hb=new Set(["flow_complete","agent_complete"]),Bf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Of=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,lr=(e,t)=>{let n=e[t];return Of(n)?n:void 0};function kc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Bi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Bb(e,t){return typeof t.type=="string"?t.type:e}function Db(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Ob(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Df(e){let t=lr(e,"result"),n=[lr(e,"tokens"),lr(e,"totalTokens"),t?lr(t,"tokens"):void 0,lr(e,"usage"),t?lr(t,"usage"):void 0];for(let o of n){if(!o)continue;let s=dn(o.output)??dn(o.outputTokens)??dn(o.completionTokens);if(s!==void 0)return s}return dn(e.outputTokens)??dn(e.completionTokens)??(t?dn(t.outputTokens)??dn(t.completionTokens):void 0)}function Nb(e){let t=lr(e,"result");return dn(e.executionTime)??dn(e.executionTimeMs)??dn(e.execution_time)??dn(e.duration)??(t?dn(t.executionTime)??dn(t.executionTimeMs):void 0)}function Fb(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Js=class{constructor(t=Fb){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:Bi(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(!Of(n)){Bf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Bb(t,n),s=this.now();if(Pb.has(o)){this.startRun(s);return}if(Rb.has(o)){this.run||this.startRun(s);return}if(Ib.has(o)){if(!Ob(o,n))return;let r=Db(n);if(!r)return;this.run||this.startRun(s);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=s),a.visibleCharCount+=r.length;let i=a.exactOutputTokens+kc(a.visibleCharCount),p=s-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Bi(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Wb.has(o)){if(!this.run)return;let r=this.run,a=Df(n);a!==void 0&&(r.exactOutputTokens+=a,r.visibleCharCount=0);let i=r.exactOutputTokens>0,p=r.exactOutputTokens+kc(r.visibleCharCount),d=this.resolveDuration(r,n,s);this.metric={status:"running",tokensPerSecond:Bi(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Hb.has(o)){if(!this.run)return;let r=this.run,a=Df(n),i=a??r.exactOutputTokens+kc(r.visibleCharCount),p=a!==void 0||r.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(r,n,s);this.metric={status:"complete",tokensPerSecond:Bi(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(Bf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let s=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return s!==void 0&&s>=250?s:Nb(n)??o-t.startedAt}};function Vr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var _b={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)"}},$b={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},jb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ub=100;function zb(e,t){let n={..._b,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return $b}function qb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Vb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),r=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${s}.${r}`}function Kb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let s=o.split("."),r=n;for(let a of s)if(r&&typeof r=="object"&&r!==null)r=r[a];else{r=void 0;break}if(typeof r=="string"&&r.trim())return r.trim()}}catch{}return null}function Gb(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 Jb(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 Xb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Qb(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 Yb(e,t,n){let o,s;try{s=JSON.parse(e.payload),o=JSON.stringify(s,null,2)}catch{s=e.payload,o=e.payload}let r=t.find(i=>i.renderEventStreamPayload);if(r?.renderEventStreamPayload&&n){let i=r.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});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 Lc(e,t,n,o,s,r,a,i){let p=s.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Vr(d,o.classNames?.eventRow);let c=a.find(y=>y.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let y=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>r(e.id)});if(y)return d.appendChild(y),d}return d.appendChild(u()),d;function u(){let y=m("div",""),f=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");f.setAttribute("data-event-id",e.id);let h=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=oe(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&h.appendChild(C);let M=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";M.textContent=P==="relative"?qb(e.timestamp,n):Vb(e.timestamp);let I=null;o.showSequenceNumbers!==!1&&(I=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(t+1));let A=zb(e.type,o.badgeColors),W=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");W.style.backgroundColor=A.bg,W.style.color=A.text,W.style.borderColor=A.text+"50",W.textContent=e.type;let $=o.descriptionFields??jb,N=Kb(e.payload,$),w=null;N&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=N);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=oe("clipboard","12px","currentColor",1.5);return Y&&V.appendChild(Y),V.addEventListener("click",async O=>{O.stopPropagation(),await Gb(Jb(e)),V.innerHTML="";let U=oe("check","12px","currentColor",1.5);U&&V.appendChild(U),setTimeout(()=>{V.innerHTML="";let me=oe("clipboard","12px","currentColor",1.5);me&&V.appendChild(me)},1500)}),f.appendChild(h),f.appendChild(M),I&&f.appendChild(I),f.appendChild(W),w&&f.appendChild(w),f.appendChild(z),f.appendChild(V),y.appendChild(f),p&&y.appendChild(Yb(e,a,i)),y}}function Nf(e){let{buffer:t,getFullHistory:n,onClose:o,config:s,plugins:r=[],getThroughput:a}=e,i=s?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=s?.features?.eventStream??{},y=r.find(h=>h.renderEventStreamView);if(y?.renderEventStreamView&&s){let h=y.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Vr(C,h?.panel);let M=[],P="",I="",A=null,W=[],$={},N=0,w=yi(),z=0,V=0,Y=!1,O=null,U=!1,me=0,be=new Set,Me=new Map,Oe="",ae="",ve=null,Z,de,ee,Ce,he=null,fe=null,Re=null;function Ne(){let D=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),q=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(Vr(q,h?.headerBar),a){fe=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),fe.style.cursor="help",he=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"),he.textContent="-- tok/s",Re=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"),Re.style.display="none",Re.style.pointerEvents="none";let Ye=fe,Ro=Re,Io=()=>{if(!Ro.textContent)return;let ra=Ye.getBoundingClientRect(),Yt=D.getBoundingClientRect();Ro.style.left=`${ra.left-Yt.left}px`,Ro.style.top=`${ra.bottom-Yt.top+4}px`,Ro.style.display="block"},Zi=()=>{Ro.style.display="none"};fe.addEventListener("mouseenter",Io),fe.addEventListener("mouseleave",Zi),fe.appendChild(he)}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 nt=m("option","");nt.value="",nt.textContent="All events (0)",Z.appendChild(nt),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 dt=oe("clipboard-copy","12px","currentColor",1.5);dt&&de.appendChild(dt);let K=m("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",de.appendChild(K),fe&&q.appendChild(fe),q.appendChild(ie),q.appendChild(Z),q.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");Vr(qe,h?.searchBar);let He=oe("search","14px","var(--persona-muted, #9ca3af)",1.5),Be=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");He&&Be.appendChild(He),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"),Vr(ee,h?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",Ce=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"),Ce.type="button",Ce.style.display="none";let Le=oe("x","12px","currentColor",2);return Le&&Ce.appendChild(Le),qe.appendChild(Be),qe.appendChild(ee),qe.appendChild(Ce),D.appendChild(q),D.appendChild(qe),Re&&D.appendChild(Re),D}let ze,Fe=r.find(D=>D.renderEventStreamToolbar);Fe?.renderEventStreamToolbar&&s?ze=Fe.renderEventStreamToolbar({config:s,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:q=>{P=q,We(),xe()},onSearchChange:q=>{I=q,We(),xe()}})??Ne():ze=Ne();let Ae=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");Ae.style.display="none";function Pe(){if(!a||!he||!fe)return;let D=a(),q=Xb(D);he.textContent=q;let ie=Qb(D);Re&&(Re.textContent=ie,ie||(Re.style.display="none")),fe.setAttribute("aria-label",ie?`Throughput: ${q}, ${ie}`:`Throughput: ${q}`)}let rt=m("div","persona-flex-1 persona-min-h-0 persona-relative"),le=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");le.style.height="100%";let Ie=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");Vr(Ie,h?.scrollIndicator),Ie.style.display="none",Ie.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Ct=oe(d,"14px","currentColor",2);Ct&&Ie.appendChild(Ct);let bt=m("span","");bt.textContent=c,Ie.appendChild(bt);let st=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");st.style.display="none",rt.appendChild(le),rt.appendChild(st),rt.appendChild(Ie),C.setAttribute("tabindex","0"),C.appendChild(ze),C.appendChild(Ae),C.appendChild(rt);function ke(){let D=t.getAll(),q={};for(let qe of D)q[qe.type]=(q[qe.type]||0)+1;let ie=Object.keys(q).sort(),nt=ie.length!==W.length||!ie.every((qe,He)=>qe===W[He]),Ee=!nt&&ie.some(qe=>q[qe]!==$[qe]),dt=D.length!==Object.values($).reduce((qe,He)=>qe+He,0);if(!nt&&!Ee&&!dt||(W=ie,$=q,!Z))return;let K=Z.value;if(Z.options[0].textContent=`All events (${D.length})`,nt){for(;Z.options.length>1;)Z.remove(1);for(let qe of ie){let He=m("option","");He.value=qe,He.textContent=`${qe} (${q[qe]||0})`,Z.appendChild(He)}K&&ie.includes(K)?Z.value=K:K&&(Z.value="",P="")}else for(let qe=1;qe<Z.options.length;qe++){let He=Z.options[qe];He.textContent=`${He.value} (${q[He.value]||0})`}}function ye(){let D=t.getAll();if(P&&(D=D.filter(q=>q.type===P)),I){let q=I.toLowerCase();D=D.filter(ie=>ie.type.toLowerCase().includes(q)||ie.payload.toLowerCase().includes(q))}return D}function ct(){return P!==""||I!==""}function We(){N=0,z=0,w.resume(),Ie.style.display="none"}function ge(D){be.has(D)?be.delete(D):be.add(D),ve=D;let q=le.scrollTop,ie=w.isFollowing();U=!0,w.pause(),xe(),le.scrollTop=q,ie&&w.resume(),U=!1}function ce(){return Mo(le,50)}function xe(){V=Date.now(),Y=!1,Pe(),ke();let D=t.getEvictedCount();D>0?(Ae.textContent=`${D.toLocaleString()} older events truncated`,Ae.style.display=""):Ae.style.display="none",M=ye();let q=M.length,ie=t.getSize()>0;q===0&&ie&&ct()?(st.textContent=I?`No events matching '${I}'`:"No events matching filter",st.style.display="",le.style.display="none"):(st.style.display="none",le.style.display=""),de&&(de.title=ct()?`Copy Filtered (${q})`:"Copy All"),p&&!w.isFollowing()&&q>N&&(z+=q-N,bt.textContent=c?`${c}${z>0?` (${z})`:""}`:"",Ie.style.display=""),N=q;let nt=t.getAll(),Ee=nt.length>0?nt[0].timestamp:0,dt=new Set(M.map(He=>He.id));for(let He of be)dt.has(He)||be.delete(He);let K=P!==Oe||I!==ae,qe=Me.size===0&&M.length>0;if(K||qe||M.length===0){le.innerHTML="",Me.clear();let He=document.createDocumentFragment();for(let Be=0;Be<M.length;Be++){let Le=Lc(M[Be],Be,Ee,u,be,ge,r,s);Me.set(M[Be].id,Le),He.appendChild(Le)}le.appendChild(He),Oe=P,ae=I,ve=null}else{if(ve!==null){let Be=Me.get(ve);if(Be&&Be.parentNode===le){let Le=M.findIndex(Ye=>Ye.id===ve);if(Le>=0){let Ye=Lc(M[Le],Le,Ee,u,be,ge,r,s);le.insertBefore(Ye,Be),Be.remove(),Me.set(ve,Ye)}}ve=null}let He=new Set(M.map(Be=>Be.id));for(let[Be,Le]of Me)He.has(Be)||(Le.remove(),Me.delete(Be));for(let Be=0;Be<M.length;Be++){let Le=M[Be];if(!Me.has(Le.id)){let Ye=Lc(Le,Be,Ee,u,be,ge,r,s);Me.set(Le.id,Ye),le.appendChild(Ye)}}}w.isFollowing()&&(le.scrollTop=le.scrollHeight)}function wt(){if(Date.now()-V>=Ub){O!==null&&(cancelAnimationFrame(O),O=null),xe();return}Y||(Y=!0,O=requestAnimationFrame(()=>{O=null,xe()}))}let F=(D,q)=>{if(!de)return;de.innerHTML="";let ie=oe(D,"12px","currentColor",1.5);ie&&de.appendChild(ie);let nt=m("span","persona-text-xs");nt.textContent="Copy All",de.appendChild(nt),setTimeout(()=>{de.innerHTML="";let Ee=oe("clipboard-copy","12px","currentColor",1.5);Ee&&de.appendChild(Ee);let dt=m("span","persona-text-xs");dt.textContent="Copy All",de.appendChild(dt),de.disabled=!1},q)},ne=async()=>{if(de){de.disabled=!0;try{let D;ct()?D=M:n?(D=await n(),D.length===0&&(D=t.getAll())):D=t.getAll();let q=D.map(ie=>{try{return JSON.parse(ie.payload)}catch{return ie.payload}});await navigator.clipboard.writeText(JSON.stringify(q,null,2)),F("check",1500)}catch{F("x",1500)}}},_e=()=>{Z&&(P=Z.value,We(),xe())},Te=()=>{!ee||!Ce||(Ce.style.display=ee.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{I=ee.value,We(),xe()},150))},k=()=>{!ee||!Ce||(ee.value="",I="",Ce.style.display="none",A&&clearTimeout(A),We(),xe())},X=()=>{if(U)return;let D=le.scrollTop,{action:q,nextLastScrollTop:ie}=bi({following:w.isFollowing(),currentScrollTop:D,lastScrollTop:me,nearBottom:ce(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});me=ie,q==="resume"?(w.resume(),z=0,Ie.style.display="none"):q==="pause"&&(w.pause(),p&&(bt.textContent=c,Ie.style.display=""))},x=D=>{let q=vi({following:w.isFollowing(),deltaY:D.deltaY,nearBottom:ce(),resumeWhenNearBottom:!0});q==="pause"?(w.pause(),p&&(bt.textContent=c,Ie.style.display="")):q==="resume"&&(w.resume(),z=0,Ie.style.display="none")},E=()=>{p&&(le.scrollTop=le.scrollHeight,w.resume(),z=0,Ie.style.display="none")},L=D=>{let q=D.target;if(!q||q.closest("button"))return;let ie=q.closest("[data-event-id]");if(!ie)return;let nt=ie.getAttribute("data-event-id");nt&&ge(nt)},B=D=>{if((D.metaKey||D.ctrlKey)&&D.key==="f"){D.preventDefault(),ee?.focus(),ee?.select();return}D.key==="Escape"&&(ee&&document.activeElement===ee?(k(),ee.blur(),C.focus()):o&&o())};de&&de.addEventListener("click",ne),Z&&Z.addEventListener("change",_e),ee&&ee.addEventListener("input",Te),Ce&&Ce.addEventListener("click",k),le.addEventListener("scroll",X),le.addEventListener("wheel",x,{passive:!0}),le.addEventListener("click",L),Ie.addEventListener("click",E),C.addEventListener("keydown",B);function J(){A&&clearTimeout(A),O!==null&&(cancelAnimationFrame(O),O=null),Y=!1,Me.clear(),de&&de.removeEventListener("click",ne),Z&&Z.removeEventListener("change",_e),ee&&ee.removeEventListener("input",Te),Ce&&Ce.removeEventListener("click",k),le.removeEventListener("scroll",X),le.removeEventListener("wheel",x),le.removeEventListener("click",L),Ie.removeEventListener("click",E),C.removeEventListener("keydown",B)}return{element:C,update:wt,destroy:J}}}function Di(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",s=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let r=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let y=u;return r.findIndex(f=>f===y||f.contains(y))},d=u=>{let y=p(u.target);if(y<0)return;let f=y;if(u.key===s)f=Math.min(y+1,r.length-1);else if(u.key===o)f=Math.max(y-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=r.length-1;else return;u.preventDefault(),f!==y&&t.onSelect(f)},c=u=>{let y=p(u.target);y>=0&&i(r[y])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,y){if(r=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let C=h===y;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||y<0&&h===0?0:-1}),a){let f=(y>=0?u[y]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Ff(e,t){let n=e.features?.artifacts?.layout,s=(n?.toolbarPreset??"default")==="document",r=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=F=>({start:F===!1?!1:typeof F=="object"&&F?F.start!==!1:!0,end:F===!1?!1:typeof F=="object"&&F?F.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),y=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,f=()=>{y?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),U?.hide()};y&&y.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=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");h.setAttribute("data-persona-theme-zone","artifact-pane"),s&&h.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"),s&&C.classList.add("persona-artifact-toolbar-document");let M=m("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=r;let P=mt({icon:"x",label:a});P.addEventListener("click",()=>{f(),t.onDismiss?.()});let I="rendered",A=Jn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:s?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:s?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:F=>{I=F==="source"?"source":"rendered",ce()}}),W=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),$=n?.documentToolbarShowCopyLabel===!0,N=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,z=!!(N&&w&&w.length>0),V=null,Y,O=null,U=null;if(s&&($||N)&&!z){if(Y=$?Gn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N){let F=oe("chevron-down",14,"currentColor",2);F&&Y.appendChild(F)}}else s&&z?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=$?Gn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=mt({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,O)):s?Y=mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Y=mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Y.classList.add("persona-hidden"));let me=s?mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):mt({icon:"refresh-cw",label:"Refresh"}),be=s?mt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):mt({icon:"x",label:a}),Me=mt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(s?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Me.classList.add("persona-hidden");let Oe=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ae=e.features?.artifacts?.toolbarActions??[],ve=()=>{let F=Ae.find(k=>k.id===Pe)??Ae[Ae.length-1],ne=F?.id??null,_e=F?.artifactType==="markdown"?F.markdown??"":"",Te=F?JSON.stringify({component:F.component,props:F.props},null,2):"";return{markdown:_e,jsonPayload:Te,id:ne}},Z=async()=>{let F=Ae.find(ne=>ne.id===Pe)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(_s(F))}catch{}};if(Y.addEventListener("click",async()=>{let F=n?.onDocumentToolbarCopyMenuSelect;if(F&&z){let{markdown:ne,jsonPayload:_e,id:Te}=ve();try{await F({actionId:"primary",artifactId:Te,markdown:ne,jsonPayload:_e})}catch{}return}await Z()}),O&&w?.length){let F=()=>h.closest("[data-persona-root]")??document.body,ne=()=>{U=To({items:w.map(_e=>({id:_e.id,label:_e.label})),onSelect:async _e=>{let{markdown:Te,jsonPayload:k,id:X}=ve(),x=n?.onDocumentToolbarCopyMenuSelect;try{x?await x({actionId:_e,artifactId:X,markdown:Te,jsonPayload:k}):_e==="markdown"||_e==="md"?await navigator.clipboard.writeText(Te):_e==="json"||_e==="source"?await navigator.clipboard.writeText(k):await navigator.clipboard.writeText(Te||k)}catch{}},anchor:V??O,position:"bottom-right",portal:F()})};h.isConnected?ne():requestAnimationFrame(ne),O.addEventListener("click",_e=>{_e.stopPropagation(),U?.toggle()})}me.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ce()}),be.addEventListener("click",()=>{f(),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(s)C.replaceChildren(),V?W.append(V,me,be):W.append(Y,me,be),W.insertBefore(Oe,be),W.insertBefore(Me,be),C.append(A.element,de,W);else{let F=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");F.append(Y,Oe,Me,P),C.appendChild(M),C.appendChild(F)}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 Ce=e.features?.artifacts?.renderTabBar,he=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),fe=Di(ee,{onSelect:F=>t.onSelect(Ae[F].id)}),Re=F=>{let ne=F.scrollWidth-F.clientWidth,_e=ne>1,Te=Math.abs(F.scrollLeft);F.classList.toggle("persona-artifact-tab-fade-start",c&&_e&&Te>1),F.classList.toggle("persona-artifact-tab-fade-end",u&&_e&&Te<ne-1)},Ne=0,ze=()=>{if(Ne)return;let F=()=>{Ne=0,Re(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(F):setTimeout(F,0)};ee.addEventListener("scroll",()=>ze(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Re(ee)).observe(ee);let Fe=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(i){for(let F of[ee,he])F.style.paddingLeft=i,F.style.paddingRight=i;Fe.style.padding=i}h.appendChild(C),h.appendChild(ee),h.appendChild(he),h.appendChild(Fe);let Ae=[],Pe=null,rt=!1,le=!0,Ie=!1,Ct=null,bt="",st=null,ke=!1,ye=F=>F.artifactType==="markdown"&&!!F.file||s?I:"rendered",ct=F=>{s||(F&&!ke?(C.insertBefore(A.element,M),ke=!0):!F&&ke&&(A.element.remove(),ke=!1))},We=()=>Pe&&Ae.find(F=>F.id===Pe)||Ae[Ae.length-1],ge=()=>{let F=Ns(We());if(!F){Oe.replaceChildren();return}let ne=ae.filter(_e=>_e.visible===void 0||_e.visible(F)).map(_e=>Fr(_e,{documentChrome:s,onClick:()=>{let Te=Ns(We());if(Te)try{Promise.resolve(_e.onClick(Te)).catch(()=>{})}catch{}}}));Oe.replaceChildren(...ne)},ce=()=>{ge();let F=s&&Ae.length<=1,ne=!!Ce;if(ee.classList.toggle("persona-hidden",F||ne),he.classList.toggle("persona-hidden",F||!ne),ne&&Ce){let k=Ae.map(X=>X.id).join("|")+" "+(Pe??"");if(k!==bt){bt=k;let X=Ce({records:Ae,selectedId:Pe,onSelect:t.onSelect});he.firstElementChild!==X&&he.replaceChildren(X)}}else{fe.beforeRender(),ee.replaceChildren();let k=[],X=-1;for(let[x,E]of Ae.entries()){let L=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");L.type="button";let B=E.artifactType==="markdown"?E.file:void 0,J=B?Wn(B.path):E.title||E.id.slice(0,8),D=B?.path||E.title||J;L.textContent=J,L.title=D,L.setAttribute("aria-label",D),E.id===Pe&&(L.classList.add("persona-bg-persona-container","persona-border-persona-border"),X=x),L.addEventListener("click",()=>t.onSelect(E.id)),ee.appendChild(L),k.push(L)}if(fe.render(k,X),X>=0&&Pe!==Ct){Ct=Pe;let x=k[X];typeof x.scrollIntoView=="function"&&x.scrollIntoView({block:"nearest",inline:"nearest"})}Re(ee)}let _e=Pe&&Ae.find(k=>k.id===Pe)||Ae[Ae.length-1];if(!_e){Fe.replaceChildren(),st=null,ct(!1);return}let Te=_e.artifactType==="markdown"?_e.file:void 0;if(ct(!!Te),s){let k=Te?wo(Te):_e.artifactType==="markdown"?"MD":_e.component??"Component",X=(_e.title||"Document").trim(),x=Te?Wn(Te.path):X.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${x} \xB7 ${k}`}else M.textContent=Te?Wn(Te.path):r;st?(st.el.parentElement!==Fe&&Fe.replaceChildren(st.el),st.update(_e)):(st=mi(_e,{config:e,resolveViewMode:ye}),Fe.replaceChildren(st.el)),Fe.classList.toggle("persona-artifact-content-flush",!!Fe.querySelector(".persona-code-pre"))},xe=()=>{let F=Ae.length>0;if(h.classList.toggle("persona-hidden",!F),y){let Te=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;F&&Te&&rt?(y.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},wt=()=>{Ie=!1,ce(),xe()};return{element:h,backdrop:y,update(F){Ae=F.artifacts,Pe=F.selectedId??F.artifacts[F.artifacts.length-1]?.id??null,Ae.length>0&&(rt=!0),Ie=!0,le&&wt()},setMobileOpen(F){rt=F,!F&&y?(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(F){let ne=oe(F?"minimize":"maximize",16,"currentColor",2);ne&&Me.replaceChildren(ne);let _e=F?"Collapse artifacts panel":"Expand artifacts panel";Me.setAttribute("aria-label",_e),Me.title=_e},setExpandToggleVisible(F){Me.classList.toggle("persona-hidden",!F)},setCopyButtonVisible(F){s||Y.classList.toggle("persona-hidden",!F)},setCustomActions(F){ae=F,ge()},setTabFade(F){let ne=d(F);ne.start===c&&ne.end===u||(c=ne.start,u=ne.end,Re(ee))},setRenderTabBar(F){F!==Ce&&(Ce=F,bt="",ce())},setVisible(F){F!==le&&(le=F,F&&Ie&&wt())}}}function Qt(e){return e?.features?.artifacts?.enabled===!0}function _f(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"),!Qt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Zb(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 $f=["panel","seamless","detached"];function Pc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&$f.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Rc(e){return!e||!Qt(e)?!1:Pc(e)==="detached"}function Xs(e,t){if(!Qt(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"),Zb(e),_f(e,t);return}let n=t.features?.artifacts?.layout,o=Pc(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 s=n?.paneBackground?.trim();s?e.style.setProperty("--persona-artifact-pane-bg",s):e.style.removeProperty("--persona-artifact-pane-bg");let r=n?.panePadding?.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):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"),_f(e,t)}function Qs(e,t){for(let i of $f)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"),!Qt(t))return;let n=t.features?.artifacts?.layout,o=Pc(t);e.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let r=n?.paneShadow?.trim();r&&e.style.setProperty("--persona-artifact-pane-shadow",r);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function jf(e,t){return!t||!Qt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function ev(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 tv(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 nv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ov(e,t,n,o){let s=e-o-2*t-n;return Math.max(0,s)}function Ic(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let r=/^([\d.]+)/.exec(o);return r?Number(r[1]):8}function Uf(e,t,n,o,s,r){let a=ev(s,200),i=ov(t,n,o,200);i=Math.max(a,i);let p=tv(r);return p!==null&&(i=Math.min(i,p)),nv(e,a,i)}var zf={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Wc=(e,t,n,o)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(r=>{if(r.dataset.enhanced==="true")return;let a=r.dataset.tvForm??"init";r.dataset.enhanced="true";let i=zf[a]??zf.init;r.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 h=m("p","persona-text-sm persona-text-persona-muted");h.textContent=i.description,p.appendChild(h)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(h=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${h.name}`;let M=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=h.label,C.appendChild(M);let P=h.type??"text",I;P==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=P),I.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",I.id=`${t.id}-${a}-${h.name}`,I.name=h.name,I.placeholder=h.placeholder??"",h.required&&(I.required=!0),C.appendChild(I),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(y),u.appendChild(f),c.appendChild(u),r.replaceChildren(p,c),c.addEventListener("submit",async h=>{h.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(c),P={};M.forEach((I,A)=>{P[A]=I}),P.type=a,f.disabled=!0,y.textContent="Submitting\u2026";try{let I=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let A=await I.json();y.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(I){y.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Hc=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(r=>r.id));return[...n.filter(r=>!o.has(r.id)),...t].sort((r,a)=>(a.priority??0)-(r.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Ys=new Hc;var qf=()=>{let e=new Map,t=(s,r)=>(e.has(s)||e.set(s,new Set),e.get(s).add(r),()=>n(s,r)),n=(s,r)=>{e.get(s)?.delete(r)};return{on:t,off:n,emit:(s,r)=>{e.get(s)?.forEach(a=>{try{a(r)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var rv=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 s=n;s<t.length;s+=1){let r=t[s];if(r==="{"&&(o+=1),r==="}"&&(o-=1,o===0))return t.slice(n,s+1)}return null},Zs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=rv(e),n=sv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...r}=o;return{type:String(s),payload:r,raw:o}}catch{return null}},Bc=e=>typeof e=="string"?e:e==null?"":String(e),cr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Bc(n.element);if(o&&t.document?.querySelector){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Bc(n.text)}}},Vf=e=>Array.isArray(e)?e.map(t=>String(t)):[],ea=e=>{let t=new Set(Vf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Vf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let r=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:r}))};return{process:r=>{if(r.streaming||r.message.role!=="assistant"||!r.text||t.has(r.message.id))return null;let a=typeof r.raw=="string"&&r.raw||typeof r.message.rawContent=="string"&&r.message.rawContent||typeof r.text=="string"&&r.text||null;!a&&typeof r.text=="string"&&r.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:r.message})||null,null):null;if(!i)return null;t.add(r.message.id),o();let p={action:i,message:r.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:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let y=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:y,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var av=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}},iv=e=>e.map(t=>({...t,streaming:!1})),lv=e=>e.map(t=>({...t,status:"complete"})),Oi=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?av(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let s={...n,messages:n.messages?iv(n.messages):void 0,artifacts:n.artifacts?lv(n.artifacts):void 0};o.setItem(e,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},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 Kr=require("partial-json");function cv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function dv(e,t){if(!cv(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 Ni(){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 s=(0,Kr.parse)(n,Kr.STR|Kr.OBJ),r=dv(s,n);r&&(e=r)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Kf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Fi(e,t){let{config:n,message:o,onPropsUpdate:s}=t,r=En.get(e.component);if(!r)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=>{s&&s(i)}};try{return r(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Gf(){let e=Ni();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Jf(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 ta(e){let t=Jf(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 _i(e){let t=Jf(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 $i(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:r="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,y=document.createElement("div");y.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,f.appendChild(C),y.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let N=1;N<=5;N++){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",`${N} star${N>1?"s":""}: ${d[N-1]}`),w.title=d[N-1],w.dataset.rating=String(N),w.innerHTML=`
41
+ `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=It(s),p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let A=a.subtitle??"Here to help you get answers fast";d.textContent=A,d.setAttribute("title",A)}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 A=a.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,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 W=parseFloat(A)||24,$=ne(a.agentIconName,W*.6,"var(--persona-text-inverse, #ffffff)",2);$?(u.appendChild($),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 y=n.querySelector("[data-role='launcher-image']");if(y){let A=a.agentIconSize??"40px";y.style.height=A,y.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=a.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let W=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,W=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let $=parseFloat(A)||24,N=Math.max($-W,8),w=ne(a.callToActionIconName,N,"currentColor",2);w?f.appendChild(w):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let h=a.position&&Mn[a.position]?Mn[a.position]:Mn["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",M="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?M:`${C} ${h}`,i||(n.style.zIndex=String(a.zIndex??zt));let P="1px solid var(--persona-border, #e5e7eb)",I="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:I,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 vf=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=yf(e),s=bf(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:y=>(p.element.replaceWith(y.header),p.element=y.header,p.iconHolder=y.iconHolder,p.headerTitle=y.headerTitle,p.headerSubtitle=y.headerSubtitle,p.closeButton=y.closeButton,p.closeButtonWrapper=y.closeButtonWrapper,p.clearChatButton=y.clearChatButton,p.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{d.footer.replaceWith(y),d.footer=y}}},xc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>vc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=vc(e,n);return{instance:r,element:r.element}};var rb=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}},sb=(e,t)=>{if(!e)return null;let n=rb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},ab=(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},ib=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Cc=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(":"))},wc=320,Af=320,lb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),cb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),db=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),pb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),ub=e=>{if(!e||e.length===0)return null;let t=Fe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Fe("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(Fe("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},fb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Hs(o.ref,{readonly:!0,render:t}))}return n},xf="\uE000",Cf="\uE001",gb=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${xf}${r}:${y}${Cf}`,a=t.map((y,f)=>y.kind==="text"?y.text:s(f)).join(""),i=n(a);if(!t.every((y,f)=>y.kind==="text"||i.includes(s(f)))){e.replaceChildren(fb(t,o));return}e.innerHTML=i;let d=new RegExp(`${xf}${r}:(\\d+)${Cf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let y=c.nextNode();y;y=c.nextNode())u.push(y);for(let y of u){let f=y;for(let h=d.exec(f.data);h;h=d.exec(f.data)){let C=t[Number(h[1])],M=f.splitText(h.index);M.data=M.data.slice(h[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(Hs(C.ref,{readonly:!0,render:o}),M),f=M}}},mb=(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=`${wc}px`,d.style.maxHeight=`${Af}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}),ib(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}},hb=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(!Cc(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=`${wc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},yb=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(!Cc(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=`${wc}px`,r.style.maxHeight=`${Af}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}},bb=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(!Cc(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}},sr=()=>{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},Ac=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:sr};if(t){let r=t(o);if(r!==null)return r}return sr()},vb=(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},wf=(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},xb=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Sc=(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 h=m("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}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],y=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let f=(h,C,M)=>{let P=gt({icon:h,label:C,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",M),P};return o&&y.appendChild(f("copy","Copy message","copy")),a&&y.appendChild(f("volume-2","Read aloud","read-aloud")),r&&y.appendChild(f("thumbs-up","Upvote","upvote")),s&&y.appendChild(f("thumbs-down","Downvote","downvote")),y},Ur=(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,y=p?.position??"left",f=d?.position??"below",h=xb(e.role,i),C=m("div",h.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=lb(e),P=e.content?.trim()??"",A=M.length>0&&P===Xa,W=xi(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,N=e.role==="assistant"&&W.type!=="none"?_r(W.type,$):null,w=e.role==="assistant"&&N?.isAnimating?.(e)===!0,q=e.role==="assistant"&&N!==null&&(!!e.streaming||w);q&&N?.bubbleClass&&C.classList.add(N.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),q&&N&&(N.containerClass&&V.classList.add(N.containerClass),V.style.setProperty("--persona-stream-step",`${W.speed}ms`),V.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let Y=q?Ci(e.content??"",W.buffer,N,e,!!e.streaming):e.content??"",O=()=>{let ee=t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent});return q&&N?.wrap==="char"?zs(ee,"char",e.id,{skipTags:N.skipTags}):q&&N?.wrap==="word"?zs(ee,"word",e.id,{skipTags:N.skipTags}):ee},U=null;if(A?(U=document.createElement("div"),U.innerHTML=O(),U.style.display="none",V.appendChild(U)):e.contentSegments?.length?gb(V,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=O(),q&&N?.useCaret&&!A&&P){let ee=wi(),we=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),he=we[we.length-1];if(he?.parentNode)he.parentNode.insertBefore(ee,he.nextSibling);else{let ue=V.lastElementChild;ue?ue.appendChild(ee):V.appendChild(ee)}}if(u&&f==="inline"&&e.createdAt){let ee=wf(e,d,"span");ee.classList.add("persona-timestamp-inline");let we=V.lastElementChild;we?we.appendChild(ee):V.appendChild(ee)}if(M.length>0){let ee=mb(M,!A&&!!P,()=>{A&&U&&(U.style.display="")});ee?C.appendChild(ee):A&&U&&(U.style.display="")}let me=cb(e);if(me.length>0){let ee=hb(me);ee&&C.appendChild(ee)}let ve=db(e);if(ve.length>0){let ee=yb(ve);ee&&C.appendChild(ee)}let Me=pb(e);if(Me.length>0){let ee=bb(Me);ee&&C.appendChild(ee)}let Oe=e.contentSegments?.length?null:ub(e.contextMentions);if(Oe&&C.appendChild(Oe),C.appendChild(V),u&&f==="below"&&e.createdAt){let ee=wf(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let ie=e.role==="assistant"?sb(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(Y&&Y.trim()),we=W.placeholder==="skeleton",he=we&&W.buffer==="line"&&ee;if(ee)he&&C.appendChild(qs());else if(we)C.appendChild(qs());else{let ue=Ac("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ue&&C.appendChild(ue)}}if(ie&&e.stopReason&&!e.streaming&&(P||(V.style.display="none"),C.appendChild(ab(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Sc(e,o,r);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=m("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ce=vb(p,e.role);return y==="right"||y==="left"&&e.role==="user"?Z.append(C,ce):Z.append(ce,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Z},Sf=(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}):Ur(e,t,n,o,r,s)};var zr=new Set,Cb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),wb=(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
+ `):""},Tf=(e,t)=>{let n=zr.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")},Tc=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&zr.has(e.id),i=n.status!=="complete",p=wb(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"),y="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),C=()=>{let ve=m("span","");return ve.setAttribute("data-tool-elapsed",h),ve.textContent=Ua(n),ve},M=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:p,isActive:i,config:t??{},elapsed:Ua(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,c.appendChild(u)):M instanceof HTMLElement?c.appendChild(M):(u.textContent=y,c.appendChild(u));let P=m("span","persona-text-xs persona-text-persona-primary");P.textContent=Gp(n),c.appendChild(P);let I=r.loadingAnimation??"none",A=f.activeTextTemplate,W=f.completeTextTemplate,$=i?A:W,N=M instanceof HTMLElement,w=(ve,Me)=>{u.textContent="";let Oe=za(ve,""),ie=0;for(let xe of Oe){let Z=xe.styles.length>0?(()=>{let ce=m("span",xe.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(ce),ce})():u;if(xe.isDuration&&i)Z.appendChild(C());else{let ce=xe.isDuration?Ua(n):xe.text;Me?ie=Ao(Z,ce,ie):Z.appendChild(document.createTextNode(ce))}}};if(!N&&$)if(P.style.display="none",u.style.display="",i&&I!=="none"){let ve=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ve}ms`),w($,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${ve}ms`),I==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w($,!0))}else w($,!1);else if(!N&&i&&I!=="none"){u.style.display="";let ve=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ve}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${ve}ms`),I==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Me=u.textContent||y;u.textContent="",Ao(u,Me,0)}n.status==="complete"&&(u.style.display="none")}else N||(n.status==="complete"?u.style.display="none":u.style.display="");let q=null;if(s){q=m("div","persona-flex persona-items-center");let Me=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?q.appendChild(Me):q.textContent=a?"Hide":"Show";let Oe=m("div","persona-flex persona-items-center persona-ml-auto");Oe.append(q),d.append(c,Oe)}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 ve=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});Cb(V,ve)||(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 O=n.chunks.join(""),U=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return U.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Y.appendChild(U),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),q){q.innerHTML="";let Me=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?q.appendChild(Me):q.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 qr=new Set,Ab=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Sb=(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
+ `);let r=ho(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
44
+ `):""},Ec=(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)"},Tb=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Sb(e,o?.previewMaxLines??3),a=n?Jp(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=Gl(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=Gl(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},Ef=(e,t,n)=>{let o=qr.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")},Mc=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(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&&qr.has(e.id),{summary:p,previewText:d,isActive:c}=Tb(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 y=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),C=()=>{let O=m("span","");return O.setAttribute("data-tool-elapsed",h),O.textContent=Ls(n),O},M=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ls(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(f.textContent=M,y.appendChild(f)):M instanceof HTMLElement?y.appendChild(M):(f.textContent=p,y.appendChild(f));let P=s.loadingAnimation??"none",I=o.activeTextTemplate,A=o.completeTextTemplate,W=c?I:A,$=M instanceof HTMLElement,N=(O,U)=>{f.textContent="";let me=n.name?.trim()||"tool",ve=za(O,me),Me=0;for(let Oe of ve){let ie=Oe.styles.length>0?(()=>{let xe=m("span",Oe.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(xe),xe})():f;if(Oe.isDuration&&c)ie.appendChild(C());else{let xe=Oe.isDuration?Ls(n):Oe.text;U?Me=Ao(ie,xe,Me):ie.appendChild(document.createTextNode(xe))}}};if(!$)if(c&&P!=="none"){let O=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),P==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),W&&N(W,!1);else if(f.classList.add(`persona-tool-loading-${P}`),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),W)N(W,!0);else{let U=f.textContent||p;f.textContent="",Ao(f,U,0)}}else W&&N(W,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=ne(i?"chevron-up":"chevron-down",16,O,2);U?w.appendChild(U):w.textContent=i?"Hide":"Show";let me=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");me.append(w),u.append(y,me)}else u.append(y);let q=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","tool"),q.style.display="none",q.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Ab(q,O)||(q.textContent=d),q.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,q),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 O=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,V.appendChild(O)}if(n.args!==void 0){let O=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let me=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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",Ec(me,o),me.textContent=ho(n.args),O.append(U,me),V.appendChild(O)}if(n.chunks&&n.chunks.length){let O=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let me=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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",Ec(me,o),me.textContent=n.chunks.join(""),O.append(U,me),V.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let me=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");me.style.fontSize="0.75rem",me.style.lineHeight="1rem",Ec(me,o),me.textContent=ho(n.result),O.append(U,me),V.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,V.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=ne(i?"chevron-up":"chevron-down",16,O,2);U?w.appendChild(U):w.textContent=i?"Hide":"Show"}V.style.display=i?"":"none",q.style.display=i?"none":q.textContent||q.childNodes.length?"":"none"})(),r.append(u,q,V),r};var ar=new Map,Wi=e=>{let n=(e.startsWith(Sn)?e.slice(Sn.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)},Mf=e=>e?.approval!==!1?e?.approval:void 0,kf=(e,t)=>{let n=Mf(t)?.detailsDisplay??"collapsed";return ar.get(e)??n==="expanded"},Lf=(e,t,n)=>{let o=Mf(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)}},Pf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=kf(e,n);Lf(o,s,n),r.style.display=s?"":"none"};var Hi=(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-max-w-[85%]","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"),y=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",y.appendChild(f),!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"),y.appendChild(w)}u.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(Sn)?As(n.toolName):void 0,M=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,I=M||(P?n.description:`The assistant wants to use \u201C${C??Wi(n.toolName)}\u201D.`),A=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=I,u.appendChild(A),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 q=m("span","persona-font-medium");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(q),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let W=o?.detailsDisplay??"collapsed",$=!!n.description&&!P,N=$||!!n.parameters;if(W!=="hidden"&&N){let w=kf(e.id,t),q=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");q.type="button",q.setAttribute("data-expand-header","true"),q.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(q.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"),q.append(V,Y),Lf(q,w,t),u.appendChild(q);let O=m("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",$){let U=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,O.appendChild(U)}if(n.parameters){let U=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&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=ho(n.parameters),O.appendChild(U)}u.appendChild(O)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let q=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");q.type="button",q.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",q.style.color=o?.approveButtonTextColor??"#ffffff",q.setAttribute("data-approval-action","approve");let V=ne("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",q.appendChild(V));let Y=document.createTextNode(o?.approveLabel??"Approve");q.appendChild(Y);let O=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");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let U=ne("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",O.appendChild(U));let me=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(me),w.append(q,O),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function Eb(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Rf(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??Eb(t),y=!1,f=null,h=()=>{if(!y)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let I=n.getBoundingClientRect(),A=i?.()??null,W=A!=null?P.top+A:P.top,$=o==="top-start"||o==="top-end"?W-r-I.height:P.bottom+r,w=o==="bottom-end"||o==="top-end"?P.right-I.width:P.left,q=a?.()??null;if(q!=null){let V=Math.max(P.left,P.right-I.width);w=Math.min(Math.max(P.left+q,P.left),V)}n.style.top=`${$}px`,n.style.left=`${w}px`},C=()=>{y&&(y=!1,f&&(f(),f=null),n.remove())},M=()=>{if(y)return;y=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let P=(t.ownerDocument??document).defaultView??window,I=t.ownerDocument??document,A=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}h()},W=N=>{let w=typeof N.composedPath=="function"?N.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},$=P.setTimeout(()=>{I.addEventListener("pointerdown",W,!0)},0);P.addEventListener("scroll",A,!0),P.addEventListener("resize",A),f=()=>{P.clearTimeout($),I.removeEventListener("pointerdown",W,!0),P.removeEventListener("scroll",A,!0),P.removeEventListener("resize",A)},d?.()};return{get isOpen(){return y},open:M,close:C,toggle:()=>y?C():M(),reposition:h,destroy:C}}function If(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Mb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Wf=(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))},ir=(e,t)=>{Wf(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)},kb=e=>e?.approval!==!1?e?.approval:void 0,Lb=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return ar.get(e)??n==="expanded"},kc=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Pb=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Sn)?As(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??Wi(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},Rb=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?Wi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Ib=(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,y=u&&Lb(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?h:f)):C.setAttribute("data-static","true");let M=m("span","persona-approval-logo"),P=ne("shield-check",16,"currentColor",2);P&&M.appendChild(P),C.appendChild(M);let I=Pb(n,o);if(u){let q=m("span","persona-approval-toggle");q.setAttribute("aria-hidden","true");let V=ne("chevron-down",14,"currentColor",2);V&&q.appendChild(V),I.append(" "),I.appendChild(q)}C.appendChild(I),i.appendChild(C);let A=m("div","persona-approval-body");if(u){let q=m("div","persona-approval-details");if(q.setAttribute("data-role","params"),q.hidden=!y,d){let V=m("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,q.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),q.appendChild(V)}A.appendChild(q)}if(n.reason){let q=m("p","persona-approval-reason");o?.reasonColor?q.style.color=o.reasonColor:o?.descriptionColor&&(q.style.color=o.descriptionColor);let V=m("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,q.append(V,document.createTextNode(n.reason)),A.appendChild(q)}let W=m("div","persona-approval-actions"),$=null,N=q=>{o?.approveButtonColor&&(q.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(q.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 q=m("div","persona-approval-split"),V=m("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),N(V),V.append(o?.approveLabel??"Always allow",kc("\u23CE"));let Y=m("button","persona-approval-caret");Y.type="button",Y.setAttribute("data-action","toggle-menu"),Y.setAttribute("aria-label","More options"),N(Y);let O=ne("chevron-down",15,"currentColor",2);O&&Y.appendChild(O),q.append(V,Y),W.append(q,w),w.append(kc("Esc"));let U=m("div","persona-approval-menu"),me=m("button","persona-approval-menu-item");me.type="button",me.append("Allow once",kc("\u2318\u23CE")),U.appendChild(me),$=Rf({anchor:q,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,$),me.addEventListener("click",()=>{ir(e,t.id),r()})}else{let q=m("button","persona-approval-primary persona-approval-primary--solo");q.type="button",q.setAttribute("data-action","allow"),N(q),q.append(o?.approveLabel??"Allow"),W.append(q,w)}return A.appendChild(W),i.appendChild(A),i.addEventListener("click",q=>{let V=q.target instanceof Element?q.target.closest("[data-action]"):null;if(!V)return;let Y=V.getAttribute("data-action");if(Y==="toggle-params"){let O=i.querySelector('[data-role="params"]');if(O){let U=O.hidden;O.hidden=!U,C.setAttribute("aria-expanded",U?"true":"false"),C.setAttribute("aria-label",U?h:f),ar.set(t.id,U)}return}if(Y==="toggle-menu"){$?.toggle();return}if(Y==="always"){ir(e,t.id),r({remember:!0});return}if(Y==="allow"){ir(e,t.id),r();return}if(Y==="deny"){ir(e,t.id),s();return}}),i},Hf=()=>{let e=Mb();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=kb(a);if(i.status!=="pending"){if(ir(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Rb(i)}Wf(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Ib(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=y=>{If(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),ir(e,o.id),y.key==="Escape"?s():y.metaKey||y.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()])ir(e,o);e.latestPendingApprovalId=null}}};var Bf=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(M=>M.role==="user"))return;let u=document.createDocumentFragment(),y=s?s.isStreaming():!1,f=h=>{switch(h){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(h=>{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=h,C.disabled=y,p?.fontFamily&&(C.style.fontFamily=f(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:h},bubbles:!0,composed:!0})),s.sendMessage(h))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let h=JSON.stringify(r);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Gs=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 Js=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 Wb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Hb=new Set(["step_start","execution_start"]),Bb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Db=new Set(["step_complete","agent_turn_complete"]),Ob=new Set(["flow_complete","agent_complete"]),Df=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Nf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,lr=(e,t)=>{let n=e[t];return Nf(n)?n:void 0};function Lc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Bi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Nb(e,t){return typeof t.type=="string"?t.type:e}function Fb(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 _b(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 Of(e){let t=lr(e,"result"),n=[lr(e,"tokens"),lr(e,"totalTokens"),t?lr(t,"tokens"):void 0,lr(e,"usage"),t?lr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(e.outputTokens)??cn(e.completionTokens)??(t?cn(t.outputTokens)??cn(t.completionTokens):void 0)}function $b(e){let t=lr(e,"result");return cn(e.executionTime)??cn(e.executionTimeMs)??cn(e.execution_time)??cn(e.duration)??(t?cn(t.executionTime)??cn(t.executionTimeMs):void 0)}function jb(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Xs=class{constructor(t=jb){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:Bi(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(!Nf(n)){Df.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Nb(t,n),r=this.now();if(Wb.has(o)){this.startRun(r);return}if(Hb.has(o)){this.run||this.startRun(r);return}if(Bb.has(o)){if(!_b(o,n))return;let s=Fb(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+Lc(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Bi(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Db.has(o)){if(!this.run)return;let s=this.run,a=Of(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+Lc(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Bi(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Ob.has(o)){if(!this.run)return;let s=this.run,a=Of(n),i=a??s.exactOutputTokens+Lc(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Bi(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(Df.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:$b(n)??o-t.startedAt}};function Vr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Ub={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)"},qb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Vb=100;function Kb(e,t){let n={...Ub,...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 Gb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Jb(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 Xb(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 Qb(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 Yb(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 Zb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ev(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 tv(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 Pc(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");Vr(d,o.classNames?.eventRow);let c=a.find(y=>y.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let y=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(y)return d.appendChild(y),d}return d.appendChild(u()),d;function u(){let y=m("div",""),f=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");f.setAttribute("data-event-id",e.id);let h=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&&h.appendChild(C);let M=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";M.textContent=P==="relative"?Gb(e.timestamp,n):Jb(e.timestamp);let I=null;o.showSequenceNumbers!==!1&&(I=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(t+1));let A=Kb(e.type,o.badgeColors),W=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");W.style.backgroundColor=A.bg,W.style.color=A.text,W.style.borderColor=A.text+"50",W.textContent=e.type;let $=o.descriptionFields??qb,N=Xb(e.payload,$),w=null;N&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=N);let q=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 O=>{O.stopPropagation(),await Qb(Yb(e)),V.innerHTML="";let U=ne("check","12px","currentColor",1.5);U&&V.appendChild(U),setTimeout(()=>{V.innerHTML="";let me=ne("clipboard","12px","currentColor",1.5);me&&V.appendChild(me)},1500)}),f.appendChild(h),f.appendChild(M),I&&f.appendChild(I),f.appendChild(W),w&&f.appendChild(w),f.appendChild(q),f.appendChild(V),y.appendChild(f),p&&y.appendChild(tv(e,a,i)),y}}function Ff(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??{},y=s.find(h=>h.renderEventStreamView);if(y?.renderEventStreamView&&r){let h=y.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Vr(C,h?.panel);let M=[],P="",I="",A=null,W=[],$={},N=0,w=yi(),q=0,V=0,Y=!1,O=null,U=!1,me=0,ve=new Set,Me=new Map,Oe="",ie="",xe=null,Z,ce,ee,we,he=null,ue=null,Re=null;function Ne(){let D=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),z=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(Vr(z,h?.headerBar),a){ue=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ue.style.cursor="help",he=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"),he.textContent="-- tok/s",Re=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"),Re.style.display="none",Re.style.pointerEvents="none";let tt=ue,Ro=Re,Io=()=>{if(!Ro.textContent)return;let sa=tt.getBoundingClientRect(),Qt=D.getBoundingClientRect();Ro.style.left=`${sa.left-Qt.left}px`,Ro.style.top=`${sa.bottom-Qt.top+4}px`,Ro.style.display="block"},el=()=>{Ro.style.display="none"};ue.addEventListener("mouseenter",Io),ue.addEventListener("mouseleave",el),ue.appendChild(he)}let re=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 Qe=m("option","");Qe.value="",Qe.textContent="All events (0)",Z.appendChild(Qe),ce=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"),ce.type="button",ce.title="Copy All";let ct=ne("clipboard-copy","12px","currentColor",1.5);ct&&ce.appendChild(ct);let G=m("span","persona-event-copy-all persona-text-xs");G.textContent="Copy All",ce.appendChild(G),ue&&z.appendChild(ue),z.appendChild(re),z.appendChild(Z),z.appendChild(ce);let ze=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Vr(ze,h?.searchBar);let Ee=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");Ee&&He.appendChild(Ee),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"),Vr(ee,h?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",we=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"),we.type="button",we.style.display="none";let Pe=ne("x","12px","currentColor",2);return Pe&&we.appendChild(Pe),ze.appendChild(He),ze.appendChild(ee),ze.appendChild(we),D.appendChild(z),D.appendChild(ze),Re&&D.appendChild(Re),D}let je,Be=s.find(D=>D.renderEventStreamToolbar);Be?.renderEventStreamToolbar&&r?je=Be.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:z=>{P=z,Le(),Ce()},onSearchChange:z=>{I=z,Le(),Ce()}})??Ne():je=Ne();let Ue=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");Ue.style.display="none";function Xe(){if(!a||!he||!ue)return;let D=a(),z=Zb(D);he.textContent=z;let re=ev(D);Re&&(Re.textContent=re,re||(Re.style.display="none")),ue.setAttribute("aria-label",re?`Throughput: ${z}, ${re}`:`Throughput: ${z}`)}let ke=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 Ie=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");Vr(Ie,h?.scrollIndicator),Ie.style.display="none",Ie.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Ct=ne(d,"14px","currentColor",2);Ct&&Ie.appendChild(Ct);let yt=m("span","");yt.textContent=c,Ie.appendChild(yt);let pt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");pt.style.display="none",ke.appendChild(oe),ke.appendChild(pt),ke.appendChild(Ie),C.setAttribute("tabindex","0"),C.appendChild(je),C.appendChild(Ue),C.appendChild(ke);function We(){let D=t.getAll(),z={};for(let ze of D)z[ze.type]=(z[ze.type]||0)+1;let re=Object.keys(z).sort(),Qe=re.length!==W.length||!re.every((ze,Ee)=>ze===W[Ee]),Te=!Qe&&re.some(ze=>z[ze]!==$[ze]),ct=D.length!==Object.values($).reduce((ze,Ee)=>ze+Ee,0);if(!Qe&&!Te&&!ct||(W=re,$=z,!Z))return;let G=Z.value;if(Z.options[0].textContent=`All events (${D.length})`,Qe){for(;Z.options.length>1;)Z.remove(1);for(let ze of re){let Ee=m("option","");Ee.value=ze,Ee.textContent=`${ze} (${z[ze]||0})`,Z.appendChild(Ee)}G&&re.includes(G)?Z.value=G:G&&(Z.value="",P="")}else for(let ze=1;ze<Z.options.length;ze++){let Ee=Z.options[ze];Ee.textContent=`${Ee.value} (${z[Ee.value]||0})`}}function ye(){let D=t.getAll();if(P&&(D=D.filter(z=>z.type===P)),I){let z=I.toLowerCase();D=D.filter(re=>re.type.toLowerCase().includes(z)||re.payload.toLowerCase().includes(z))}return D}function Ze(){return P!==""||I!==""}function Le(){N=0,q=0,w.resume(),Ie.style.display="none"}function ge(D){ve.has(D)?ve.delete(D):ve.add(D),xe=D;let z=oe.scrollTop,re=w.isFollowing();U=!0,w.pause(),Ce(),oe.scrollTop=z,re&&w.resume(),U=!1}function le(){return Mo(oe,50)}function Ce(){V=Date.now(),Y=!1,Xe(),We();let D=t.getEvictedCount();D>0?(Ue.textContent=`${D.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",M=ye();let z=M.length,re=t.getSize()>0;z===0&&re&&Ze()?(pt.textContent=I?`No events matching '${I}'`:"No events matching filter",pt.style.display="",oe.style.display="none"):(pt.style.display="none",oe.style.display=""),ce&&(ce.title=Ze()?`Copy Filtered (${z})`:"Copy All"),p&&!w.isFollowing()&&z>N&&(q+=z-N,yt.textContent=c?`${c}${q>0?` (${q})`:""}`:"",Ie.style.display=""),N=z;let Qe=t.getAll(),Te=Qe.length>0?Qe[0].timestamp:0,ct=new Set(M.map(Ee=>Ee.id));for(let Ee of ve)ct.has(Ee)||ve.delete(Ee);let G=P!==Oe||I!==ie,ze=Me.size===0&&M.length>0;if(G||ze||M.length===0){oe.innerHTML="",Me.clear();let Ee=document.createDocumentFragment();for(let He=0;He<M.length;He++){let Pe=Pc(M[He],He,Te,u,ve,ge,s,r);Me.set(M[He].id,Pe),Ee.appendChild(Pe)}oe.appendChild(Ee),Oe=P,ie=I,xe=null}else{if(xe!==null){let He=Me.get(xe);if(He&&He.parentNode===oe){let Pe=M.findIndex(tt=>tt.id===xe);if(Pe>=0){let tt=Pc(M[Pe],Pe,Te,u,ve,ge,s,r);oe.insertBefore(tt,He),He.remove(),Me.set(xe,tt)}}xe=null}let Ee=new Set(M.map(He=>He.id));for(let[He,Pe]of Me)Ee.has(He)||(Pe.remove(),Me.delete(He));for(let He=0;He<M.length;He++){let Pe=M[He];if(!Me.has(Pe.id)){let tt=Pc(Pe,He,Te,u,ve,ge,s,r);Me.set(Pe.id,tt),oe.appendChild(tt)}}}w.isFollowing()&&(oe.scrollTop=oe.scrollHeight)}function wt(){if(Date.now()-V>=Vb){O!==null&&(cancelAnimationFrame(O),O=null),Ce();return}Y||(Y=!0,O=requestAnimationFrame(()=>{O=null,Ce()}))}let be=(D,z)=>{if(!ce)return;ce.innerHTML="";let re=ne(D,"12px","currentColor",1.5);re&&ce.appendChild(re);let Qe=m("span","persona-text-xs");Qe.textContent="Copy All",ce.appendChild(Qe),setTimeout(()=>{ce.innerHTML="";let Te=ne("clipboard-copy","12px","currentColor",1.5);Te&&ce.appendChild(Te);let ct=m("span","persona-text-xs");ct.textContent="Copy All",ce.appendChild(ct),ce.disabled=!1},z)},fe=async()=>{if(ce){ce.disabled=!0;try{let D;Ze()?D=M:n?(D=await n(),D.length===0&&(D=t.getAll())):D=t.getAll();let z=D.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),be("check",1500)}catch{be("x",1500)}}},hn=()=>{Z&&(P=Z.value,Le(),Ce())},Q=()=>{!ee||!we||(we.style.display=ee.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{I=ee.value,Le(),Ce()},150))},k=()=>{!ee||!we||(ee.value="",I="",we.style.display="none",A&&clearTimeout(A),Le(),Ce())},F=()=>{if(U)return;let D=oe.scrollTop,{action:z,nextLastScrollTop:re}=bi({following:w.isFollowing(),currentScrollTop:D,lastScrollTop:me,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});me=re,z==="resume"?(w.resume(),q=0,Ie.style.display="none"):z==="pause"&&(w.pause(),p&&(yt.textContent=c,Ie.style.display=""))},v=D=>{let z=vi({following:w.isFollowing(),deltaY:D.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});z==="pause"?(w.pause(),p&&(yt.textContent=c,Ie.style.display="")):z==="resume"&&(w.resume(),q=0,Ie.style.display="none")},S=()=>{p&&(oe.scrollTop=oe.scrollHeight,w.resume(),q=0,Ie.style.display="none")},L=D=>{let z=D.target;if(!z||z.closest("button"))return;let re=z.closest("[data-event-id]");if(!re)return;let Qe=re.getAttribute("data-event-id");Qe&&ge(Qe)},B=D=>{if((D.metaKey||D.ctrlKey)&&D.key==="f"){D.preventDefault(),ee?.focus(),ee?.select();return}D.key==="Escape"&&(ee&&document.activeElement===ee?(k(),ee.blur(),C.focus()):o&&o())};ce&&ce.addEventListener("click",fe),Z&&Z.addEventListener("change",hn),ee&&ee.addEventListener("input",Q),we&&we.addEventListener("click",k),oe.addEventListener("scroll",F),oe.addEventListener("wheel",v,{passive:!0}),oe.addEventListener("click",L),Ie.addEventListener("click",S),C.addEventListener("keydown",B);function K(){A&&clearTimeout(A),O!==null&&(cancelAnimationFrame(O),O=null),Y=!1,Me.clear(),ce&&ce.removeEventListener("click",fe),Z&&Z.removeEventListener("change",hn),ee&&ee.removeEventListener("input",Q),we&&we.removeEventListener("click",k),oe.removeEventListener("scroll",F),oe.removeEventListener("wheel",v),oe.removeEventListener("click",L),Ie.removeEventListener("click",S),C.removeEventListener("keydown",B)}return{element:C,update:wt,destroy:K}}}function Di(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 y=u;return s.findIndex(f=>f===y||f.contains(y))},d=u=>{let y=p(u.target);if(y<0)return;let f=y;if(u.key===r)f=Math.min(y+1,s.length-1);else if(u.key===o)f=Math.max(y-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==y&&t.onSelect(f)},c=u=>{let y=p(u.target);y>=0&&i(s[y])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,y){if(s=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let C=h===y;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||y<0&&h===0?0:-1}),a){let f=(y>=0?u[y]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function _f(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),y=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,f=()=>{y?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),U?.hide()};y&&y.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=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");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.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 M=m("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let P=gt({icon:"x",label:a});P.addEventListener("click",()=>{f(),t.onDismiss?.()});let I="rendered",A=Jn({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=>{I=Q==="source"?"source":"rendered",be()}}),W=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),$=n?.documentToolbarShowCopyLabel===!0,N=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,q=!!(N&&w&&w.length>0),V=null,Y,O=null,U=null;if(r&&($||N)&&!q){if(Y=$?Gn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N){let Q=ne("chevron-down",14,"currentColor",2);Q&&Y.appendChild(Q)}}else r&&q?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=$?Gn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=gt({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,O)):r?Y=gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Y=gt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Y.classList.add("persona-hidden"));let me=r?gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):gt({icon:"refresh-cw",label:"Refresh"}),ve=r?gt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):gt({icon:"x",label:a}),Me=gt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Me.classList.add("persona-hidden");let Oe=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ie=e.features?.artifacts?.toolbarActions??[],xe=()=>{let Q=ke.find(S=>S.id===oe)??ke[ke.length-1],k=Q?.id??null,F=Q?.artifactType==="markdown"?Q.markdown??"":"",v=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:F,jsonPayload:v,id:k}},Z=async()=>{let Q=ke.find(k=>k.id===oe)??ke[ke.length-1];try{await navigator.clipboard.writeText($s(Q))}catch{}};if(Y.addEventListener("click",async()=>{let Q=n?.onDocumentToolbarCopyMenuSelect;if(Q&&q){let{markdown:k,jsonPayload:F,id:v}=xe();try{await Q({actionId:"primary",artifactId:v,markdown:k,jsonPayload:F})}catch{}return}await Z()}),O&&w?.length){let Q=()=>h.closest("[data-persona-root]")??document.body,k=()=>{U=To({items:w.map(F=>({id:F.id,label:F.label})),onSelect:async F=>{let{markdown:v,jsonPayload:S,id:L}=xe(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:F,artifactId:L,markdown:v,jsonPayload:S}):F==="markdown"||F==="md"?await navigator.clipboard.writeText(v):F==="json"||F==="source"?await navigator.clipboard.writeText(S):await navigator.clipboard.writeText(v||S)}catch{}},anchor:V??O,position:"bottom-right",portal:Q()})};h.isConnected?k():requestAnimationFrame(k),O.addEventListener("click",F=>{F.stopPropagation(),U?.toggle()})}me.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}be()}),ve.addEventListener("click",()=>{f(),t.onDismiss?.()});let ce=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?W.append(V,me,ve):W.append(Y,me,ve),W.insertBefore(Oe,ve),W.insertBefore(Me,ve),C.append(A.element,ce,W);else{let Q=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Q.append(Y,Oe,Me,P),C.appendChild(M),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 we=e.features?.artifacts?.renderTabBar,he=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ue=Di(ee,{onSelect:Q=>t.onSelect(ke[Q].id)}),Re=Q=>{let k=Q.scrollWidth-Q.clientWidth,F=k>1,v=Math.abs(Q.scrollLeft);Q.classList.toggle("persona-artifact-tab-fade-start",c&&F&&v>1),Q.classList.toggle("persona-artifact-tab-fade-end",u&&F&&v<k-1)},Ne=0,je=()=>{if(Ne)return;let Q=()=>{Ne=0,Re(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};ee.addEventListener("scroll",()=>je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Re(ee)).observe(ee);let Be=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ue=()=>{Be.scrollLeft=0},Xe=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ue):setTimeout(Ue,0)};if(i){for(let Q of[ee,he])Q.style.paddingLeft=i,Q.style.paddingRight=i;Be.style.padding=i}h.appendChild(C),h.appendChild(ee),h.appendChild(he),h.appendChild(Be);let ke=[],oe=null,Ie=!1,Ct=!1,yt=!0,pt=!1,We=null,ye="",Ze=null,Le=!1,ge=Q=>Q.artifactType==="markdown"&&!!Q.file||r?I:"rendered",le=Q=>{r||(Q&&!Le?(C.insertBefore(A.element,M),Le=!0):!Q&&Le&&(A.element.remove(),Le=!1))},Ce=()=>oe&&ke.find(Q=>Q.id===oe)||ke[ke.length-1],wt=()=>{let Q=Fs(Ce());if(!Q){Oe.replaceChildren();return}let k=ie.filter(F=>F.visible===void 0||F.visible(Q)).map(F=>Fr(F,{documentChrome:r,onClick:()=>{let v=Fs(Ce());if(v)try{Promise.resolve(F.onClick(v)).catch(()=>{})}catch{}}}));Oe.replaceChildren(...k)},be=()=>{wt();let Q=r&&ke.length<=1,k=!!we;if(ee.classList.toggle("persona-hidden",Q||k),he.classList.toggle("persona-hidden",Q||!k),k&&we){let S=ke.map(L=>L.id).join("|")+" "+(oe??"");if(S!==ye){ye=S;let L=we({records:ke,selectedId:oe,onSelect:t.onSelect});he.firstElementChild!==L&&he.replaceChildren(L)}}else{ue.beforeRender(),ee.replaceChildren();let S=[],L=-1;for(let[B,K]of ke.entries()){let D=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");D.type="button";let z=K.artifactType==="markdown"?K.file:void 0,re=z?Wn(z.path):K.title||K.id.slice(0,8),Qe=z?.path||K.title||re;D.textContent=re,D.title=Qe,D.setAttribute("aria-label",Qe),K.id===oe&&(D.classList.add("persona-bg-persona-container","persona-border-persona-border"),L=B),D.addEventListener("click",()=>t.onSelect(K.id)),ee.appendChild(D),S.push(D)}if(ue.render(S,L),L>=0&&oe!==We){We=oe;let B=S[L];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}Re(ee)}let F=oe&&ke.find(S=>S.id===oe)||ke[ke.length-1];if(!F){Be.replaceChildren(),Ze=null,le(!1);return}let v=F.artifactType==="markdown"?F.file:void 0;if(le(!!v),r){let S=v?wo(v):F.artifactType==="markdown"?"MD":F.component??"Component",L=(F.title||"Document").trim(),B=v?Wn(v.path):L.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${B} \xB7 ${S}`}else M.textContent=v?Wn(v.path):s;Ze?(Ze.el.parentElement!==Be&&Be.replaceChildren(Ze.el),Ze.update(F)):(Ze=mi(F,{config:e,resolveViewMode:ge}),Be.replaceChildren(Ze.el)),Be.classList.toggle("persona-artifact-content-flush",!!Be.querySelector(".persona-code-pre"))},fe=()=>{let Q=ke.length>0;if(h.classList.toggle("persona-hidden",!Q),y){let v=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Q&&v&&Ie?(y.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},hn=()=>{pt=!1,be(),fe()};return{element:h,backdrop:y,update(Q){let k=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,F=k!==oe;ke=Q.artifacts,oe=k,ke.length>0&&(Ie=!0),pt=!0,yt&&hn(),F&&Ue()},setMobileOpen(Q){Ie=Q,!Q&&y?(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):fe()},setExpanded(Q){Q!==Ct&&(Ct=Q,Xe());let k=ne(Q?"minimize":"maximize",16,"currentColor",2);k&&Me.replaceChildren(k);let F=Q?"Collapse artifacts panel":"Expand artifacts panel";Me.setAttribute("aria-label",F),Me.title=F},setExpandToggleVisible(Q){Me.classList.toggle("persona-hidden",!Q)},setCopyButtonVisible(Q){r||Y.classList.toggle("persona-hidden",!Q)},setCustomActions(Q){ie=Q,wt()},setTabFade(Q){let k=d(Q);k.start===c&&k.end===u||(c=k.start,u=k.end,Re(ee))},setRenderTabBar(Q){Q!==we&&(we=Q,ye="",be())},setVisible(Q){Q!==yt&&(yt=Q,Q&&pt&&hn())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function $f(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 nv(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 jf=["panel","seamless","detached"];function Rc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&jf.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Ic(e){return!e||!Xt(e)?!1:Rc(e)==="detached"}function Qs(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"),nv(e),$f(e,t);return}let n=t.features?.artifacts?.layout,o=Rc(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"),$f(e,t)}function Ys(e,t){for(let i of jf)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=Rc(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 Uf(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function ov(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 rv(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 sv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function av(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Wc(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 zf(e,t,n,o,r,s){let a=ov(r,200),i=av(t,n,o,200);i=Math.max(a,i);let p=rv(s);return p!==null&&(i=Math.min(i,p)),sv(e,a,i)}var qf={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"}},Hc=(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=qf[a]??qf.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 h=m("p","persona-text-sm persona-text-persona-muted");h.textContent=i.description,p.appendChild(h)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(h=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${h.name}`;let M=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=h.label,C.appendChild(M);let P=h.type??"text",I;P==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=P),I.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",I.id=`${t.id}-${a}-${h.name}`,I.name=h.name,I.placeholder=h.placeholder??"",h.required&&(I.required=!0),C.appendChild(I),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(y),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async h=>{h.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(c),P={};M.forEach((I,A)=>{P[A]=I}),P.type=a,f.disabled=!0,y.textContent="Submitting\u2026";try{let I=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let A=await I.json();y.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(I){y.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Bc=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()}},Zs=new Bc;var Vf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Kf=(e,t,n)=>{if(!Vf(e)||!Vf(t)||iv.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]=Kf(e[r],t[r],s)}return o};function Oi(e,t){let n=Kf(e,t,"");return Br(n)}var Gf=()=>{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 lv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},cv=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},ea=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=lv(e),n=cv(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),cr={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)}}},Jf=e=>Array.isArray(e)?e.map(t=>String(t)):[],ta=e=>{let t=new Set(Jf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Jf(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 y=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:y,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var dv=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}},pv=e=>e.map(t=>({...t,streaming:!1})),uv=e=>e.map(t=>({...t,status:"complete"})),Ni=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?dv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?pv(n.messages):void 0,artifacts:n.artifacts?uv(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 Kr=require("partial-json");function fv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function gv(e,t){if(!fv(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 Fi(){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,Kr.parse)(n,Kr.STR|Kr.OBJ),s=gv(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Xf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _i(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=En.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 Qf(){let e=Fi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Yf(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 na(e){let t=Yf(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 $i(e){let t=Yf(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 mv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ji(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=mv}=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,y=document.createElement("div");y.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),y.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let N=1;N<=5;N++){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",`${N} star${N>1?"s":""}: ${d[N-1]}`),w.title=d[N-1],w.dataset.rating=String(N),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=N,P.forEach((z,V)=>{let Y=V<N;z.classList.toggle("selected",Y),z.setAttribute("aria-checked",V===N-1?"true":"false")})}),P.push(w),M.appendChild(w)}y.appendChild(M);let I=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=r,I.rows=3,I.setAttribute("aria-label","Additional comments"),N.appendChild(I),y.appendChild(N)}let A=document.createElement("div");A.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{n?.(),c.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=a,$.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let N=I?.value.trim()||void 0;await t(u,N),c.remove()}catch(N){$.disabled=!1,$.textContent=a,console.error("[CSAT Feedback] Failed to submit:",N)}}),A.appendChild(W),A.appendChild($),y.appendChild(A),c.appendChild(y),c}function ji(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:r="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 y=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,h.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,h.appendChild(M),f.appendChild(h);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 I=document.createElement("div");I.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=d;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=c,I.appendChild(A),I.appendChild(W);let $=document.createElement("div");$.className="persona-feedback-numbers";let N=[];for(let O=0;O<=10;O++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${O} out of 10`),U.textContent=String(O),U.dataset.rating=String(O),O<=6?U.classList.add("persona-feedback-detractor"):O<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{y=O,N.forEach((me,be)=>{me.classList.toggle("selected",be===O),me.setAttribute("aria-checked",be===O?"true":"false")})}),N.push(U),$.appendChild(U)}P.appendChild(I),P.appendChild($),f.appendChild(P);let w=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=r,w.rows=3,w.setAttribute("aria-label","Additional comments"),O.appendChild(w),f.appendChild(O)}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(y===null){$.classList.add("persona-feedback-shake"),setTimeout(()=>$.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(y,O),u.remove()}catch(O){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),z.appendChild(V),z.appendChild(Y),f.appendChild(z),u.appendChild(f),u}var Gr="persona-chat-history",uv=30*1e3,fv=641,gv={"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 mv(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 s=o.getAsFile();if(!s)continue;if(s.name){t.push(s);continue}let r=gv[s.type]??"png";t.push(new File([s],`clipboard-image-${Date.now()}.${r}`,{type:s.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 Ui(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 hv(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 yv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Dc=e=>!e||typeof e!="object"?{}:{...e},Xf=e=>e.map(t=>({...t,streaming:!1})),Qf=(e,t,n)=>{let o=e?.markdown?Jo(e.markdown):null,s=Tr(e?.sanitize);return e?.postprocessMessage&&s&&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."),r=>{let a=r.text??"",i=r.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:r.message,streaming:r.streaming});c!==null&&(a=c.text,c.persist||(r.message.__skipPersist=!0),c.resubmit&&!r.streaming&&n&&n())}let p=jn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...r,text:a,raw:i??r.text??""});d=s?s(c):c}else if(o){let c=r.streaming?Tp(a):a,u=o(c);d=s&&p?s(u):u}else d=Rn(a);return d}};function Yf(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",s=e?.iconColor??"rgba(59, 130, 246, 0.6)",r=e?.iconStrokeWidth??.5,a=oe(n,o,s,r);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 bv=(e,t)=>{let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];n[o]=r?{...r,...s}:s}return n},vv=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:bv(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),zi=(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=oi(t),s=Ys.getForInstance(o.plugins),{plugin:r,teardown:a}=Wf();o.components&&En.registerAll(o.components);let i=qf(),d=o.persistState===!1?null:o.storageAdapter??Oi(),c={},u=null,y=!1,f=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:v}=g;return v&&(y=!0),b}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(g=>f(g??{messages:[],metadata:{}}));else{let b=f(l??{messages:[],metadata:{}});b.metadata&&(c=Dc(b.metadata)),b.messages?.length&&(o={...o,initialMessages:b.messages}),b.artifacts?.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=f({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let h=()=>c,C=l=>{c=l({...c})??{},ml()},M=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zs],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[cr.message,cr.messageAndClick],I=ea({parsers:M,handlers:P,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});I.syncFromMetadata();let A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,$=o.autoFocusInput??!1,N=W,w=A,z=o.layout?.header?.layout,V=!1,Y=()=>Lo(o),O=()=>A||Y(),U=Y()?!1:A?W:!0,me=!1,be=null,Me=()=>{me=!0,be&&clearTimeout(be),be=setTimeout(()=>{me&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),me=!1)},1e4)},Oe=Qf(o,I,Me),ae=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,de=o.features?.scrollToBottom??{},ee=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,fe=Z?new Gs(he):null,Re=o.features?.eventStream?.maxEvents??2e3,Ne=Z?new Ks(Re,fe):null,ze=Z?new Js:null,Fe=null,Ae=!1,Pe=null,rt=0;fe?.open().then(()=>Ne?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let le={onCopy:l=>{i.emit("message:copy",l),j?.isClientTokenMode()&&j.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),j?.isClientTokenMode()&&j.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},Ie=o.statusIndicator??{},Ct=l=>l==="idle"?Ie.idleText??Dt.idle:l==="connecting"?Ie.connectingText??Dt.connecting:l==="connected"?Ie.connectedText??Dt.connected:l==="error"?Ie.errorText??Dt.error:l==="paused"?Ie.pausedText??Dt.paused:l==="resuming"?Ie.resumingText??Dt.resuming:Dt[l];function bt(l,g,b,v){if(v==="idle"&&b.idleLink){l.textContent="";let T=document.createElement("a");T.href=b.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=g}let st=bf({config:o,showClose:O()}),{wrapper:ke,panel:ye,pillRoot:ct}=st.shell,We=st.panelElements,{container:ge,body:ce,messagesWrapper:xe,suggestions:wt,textarea:F,sendButton:ne,sendButtonWrapper:_e,composerForm:Te,statusText:k,introTitle:X,introSubtitle:x,closeButton:E,iconHolder:L,headerTitle:B,headerSubtitle:J,header:D,footer:q,actionsRow:ie,rightActions:nt}=We,Ee=We.leftActions,dt=We.setSendButtonMode,K=We.micButton,qe=We.micButtonWrapper,He=We.attachmentButton,Be=We.attachmentButtonWrapper,Le=We.attachmentInput,Ye=We.attachmentPreviewsContainer;ge.classList.add("persona-relative"),ce.classList.add("persona-relative");let Ro=12,Io=()=>de.label??"",Zi=()=>de.iconName??"arrow-down",ra=()=>de.enabled!==!1,Yt=()=>ee.mode??"anchor-top",Yn=()=>Yt()==="follow"||Yt()==="anchor-top"&&os,Zc=()=>ee.anchorTopOffset??16,$g=()=>ee.restorePosition??"bottom",ed=()=>ee.pauseOnInteraction===!0,td=()=>ee.showActivityWhilePinned!==!1,nd=()=>ee.announce===!0,Ht=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");Ht.type="button",Ht.style.display="none",Ht.setAttribute("data-persona-scroll-to-bottom","true");let Jr=m("span","persona-flex persona-items-center"),el=m("span",""),Wo=m("span","");Wo.setAttribute("data-persona-scroll-to-bottom-count",""),Wo.style.display="none",Ht.append(Jr,el,Wo),ge.appendChild(Ht);let Zn=m("div","persona-stream-anchor-spacer");Zn.setAttribute("aria-hidden","true"),Zn.setAttribute("data-persona-anchor-spacer",""),Zn.style.flexShrink="0",Zn.style.pointerEvents="none",Zn.style.height="0px",ce.appendChild(Zn);let Ho=m("div","persona-sr-only");Ho.setAttribute("aria-live","polite"),Ho.setAttribute("aria-atomic","true"),Ho.setAttribute("role","status"),Ho.setAttribute("data-persona-live-region",""),Object.assign(Ho.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(Ho);let Xr=null,sa=null,od=l=>{!nd()||!l||(sa=l,Xr===null&&(Xr=setTimeout(()=>{Xr=null,sa&&nd()&&(Ho.textContent=sa),sa=null},400)))},dr=()=>{let g=q.style.display==="none"?0:q.offsetHeight;Ht.style.bottom=`${g+Ro}px`};dr();let rd=()=>{let l=!!Io();Ht.setAttribute("aria-label",Io()||"Jump to latest"),Ht.title=Io(),Ht.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Jr.innerHTML="";let g=oe(Zi(),"14px","currentColor",2);g?(Jr.appendChild(g),Jr.style.display=""):Jr.style.display="none",el.textContent=Io(),el.style.display=l?"":"none"};rd();let Lt=null,nn=null,sd=null,ad=s.find(l=>l.renderHeader);if(ad?.renderHeader){let l=ad.renderHeader({config:o,defaultRenderer:()=>{let g=Xn({config:o,showClose:O()});return rr(ge,g,o),g.header},onClose:()=>yt(!1,"user")});if(l){let g=ge.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),D=l,st.header.element=l)}}let tl=()=>{if(!Ne)return;if(Ae=!0,!Fe&&Ne&&(Fe=Nf({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Qr(),config:o,plugins:s,getThroughput:()=>ze?.getMetric()??{status:"idle"}})),Fe&&(ce.style.display="none",q.parentNode?.insertBefore(Fe.element,q),Fe.update()),it){it.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(b=>b&&it.classList.add(b))}let l=()=>{if(!Ae)return;let g=Date.now();g-rt>=200&&(Fe?.update(),rt=g),Pe=requestAnimationFrame(l)};rt=0,Pe=requestAnimationFrame(l),rn(),i.emit("eventStream:opened",{timestamp:Date.now()})},Qr=()=>{if(Ae){if(Ae=!1,Fe&&Fe.element.remove(),ce.style.display="",it){it.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&it.classList.remove(g))}Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),rn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},it=null;if(Z){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");it=m("button",g),it.style.width="28px",it.style.height="28px",it.style.color=Xt.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let b=oe("activity","18px","currentColor",1.5);b&&it.appendChild(b);let v=We.clearChatButtonWrapper,T=We.closeButtonWrapper,R=v||T;R&&R.parentNode===D?D.insertBefore(it,R):D.appendChild(it),it.addEventListener("click",()=>{Ae?Qr():tl()})}let jg=l=>{let g=o.attachments;if(!g?.enabled)return;let b=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!b){b=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let T=l.querySelector("[data-persona-composer-form]");T?.parentNode?T.parentNode.insertBefore(b,T):l.insertBefore(b,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let T=m("input");T.type="file",T.setAttribute("data-persona-composer-attachment-input",""),T.accept=(g.allowedTypes??Kn).join(","),T.multiple=(g.maxFiles??4)>1,T.style.display="none",T.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(T)}},id=s.find(l=>l.renderComposer);if(id?.renderComposer){let l=o.composer,g=id.renderComposer({config:o,defaultRenderer:()=>jr({config:o}).footer,onSubmit:b=>{if(!j||j.isStreaming())return;let v=b.trim(),T=Lt?.hasAttachments()??!1;if(!v&&!T)return;Dd();let R;T&&(R=[],R.push(...Lt.getContentParts()),v&&R.push(bo(v))),j.sendMessage(v,{contentParts:R}),T&&Lt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Le?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{sd?.()}:void 0});g&&(st.replaceComposer(g),q=st.composer.footer)}let Ug=l=>{let g=(...pe)=>{for(let se of pe){let we=l.querySelector(se);if(we)return we}return null},b=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),Q=l.querySelector("[data-persona-composer-status]");b&&(Te=b),v&&(F=v),T&&(ne=T),R&&(K=R,qe=R.parentElement),Q&&(k=Q);let _=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(wt=_);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(He=G,Be=G.parentElement),Le=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(ie=re),Ee=g(".persona-widget-composer__left-actions")};jg(q),Ug(q);let eo=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(eo&&(xe.style.maxWidth=eo,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%"),eo&&Te&&!Y()&&(Te.style.maxWidth=eo,Te.style.marginLeft="auto",Te.style.marginRight="auto"),eo&&wt&&!Y()&&(wt.style.maxWidth=eo,wt.style.marginLeft="auto",wt.style.marginRight="auto"),eo&&Ye&&!Y()&&(Ye.style.maxWidth=eo,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&Le&&Ye){Lt=tr.fromConfig(o.attachments),Lt.setPreviewsContainer(Ye),Le.addEventListener("change",b=>{let v=b.target;Lt?.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,g=Yf(l);ge.appendChild(g)}let zg=()=>nn?.prefetch();if(o.contextMentions?.enabled&&F&&(nn=Eu({config:o,textarea:F,anchor:Te??F,getMessages:()=>j.getMessages(),liveRegionHost:ge}),nn)){let l=F;l.parentElement?.insertBefore(nn.contextRow,l);let g=nn.affordanceButtons;for(let b=g.length-1;b>=0;b--){let v=g[b];Ee?Ee.insertBefore(v,Ee.firstChild):Te?.appendChild(v)}}(()=>{let l=o.layout?.slots??{},g=v=>{switch(v){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 wt;case"composer":return Te;case"footer-bottom":return k;default:return null}},b=(v,T)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")D.insertBefore(T,D.firstChild);else if(v==="header-right")D.appendChild(T);else{let R=D.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(T,R.nextSibling):D.appendChild(T)}break;case"body-top":{let R=ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(T):ce.insertBefore(T,ce.firstChild);break}case"body-bottom":ce.appendChild(T);break;case"footer-top":wt.replaceWith(T);break;case"footer-bottom":k.replaceWith(T);break;default:break}};for(let[v,T]of Object.entries(l))if(T)try{let R=T({config:o,defaultContent:()=>g(v)});R&&b(v,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,R)}})();let ld=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let v=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let T=v.getAttribute("data-message-id");if(!T)return;let R=b.getAttribute("data-bubble-type");if(R==="reasoning")zr.has(T)?zr.delete(T):zr.add(T),Sf(T,v);else if(R==="tool")qr.has(T)?qr.delete(T):qr.add(T),Tf(T,v,o);else if(R==="approval"){let _=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=ar.get(T)??_;ar.set(T,!G),Lf(T,v,o)}No.delete(T)};xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ld(l))}),xe.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ld(l))}),xe.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let b=xe.getRootNode(),v=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let T=v.toString(),R=Qu(T);!R||R===T||(g.setData("text/plain",R),l.preventDefault())});let nl=new Map,cd=null,dd="idle",qg={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Vg=(l,g)=>{let{icon:b,label:v}=qg[g];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let T=oe(b,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},pd=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let v=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Vg(g,v&&v===cd?dd:"idle")})};xe.addEventListener("click",l=>{let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.closest("[data-actions-for]");if(!v)return;let T=v.getAttribute("data-actions-for");if(!T)return;let R=b.getAttribute("data-action");if(R==="copy"){let _=j.getMessages().find(G=>G.id===T);if(_&&le.onCopy){let G=_.content||"";navigator.clipboard.writeText(G).then(()=>{b.classList.add("persona-message-action-success");let re=oe("check",14,"currentColor",2);re&&(b.innerHTML="",b.appendChild(re)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let pe=oe("copy",14,"currentColor",2);pe&&(b.innerHTML="",b.appendChild(pe))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),le.onCopy(_)}}else if(R==="read-aloud")j.toggleReadAloud(T);else if(R==="upvote"||R==="downvote"){let _=(nl.get(T)??null)===R,G=R==="upvote"?"thumbs-up":"thumbs-down";if(_){nl.delete(T),b.classList.remove("persona-message-action-active");let re=oe(G,14,"currentColor",2);re&&(b.innerHTML="",b.appendChild(re))}else{let re=R==="upvote"?"downvote":"upvote",pe=v.querySelector(`[data-action="${re}"]`);if(pe){pe.classList.remove("persona-message-action-active");let lt=oe(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);lt&&(pe.innerHTML="",pe.appendChild(lt))}nl.set(T,R),b.classList.add("persona-message-action-active");let se=oe(G,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(se)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Je=j.getMessages().find(vt=>vt.id===T);Je&&le.onFeedback&&le.onFeedback({type:R,messageId:Je.id,message:Je})}}}),xe.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.closest(".persona-approval-bubble");if(!v)return;let T=v.getAttribute("data-message-id");if(!T)return;let R=b.getAttribute("data-approval-action");if(!R)return;let Q=R==="approve"?"approved":"denied",G=j.getMessages().find(pe=>pe.id===T);if(!G?.approval)return;let re=v.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?j.resolveWebMcpApproval(T,Q):j.resolveApproval(G.approval,Q)});let Ze=null,Yr=null,Zr=()=>{},es="none",aa=null,yn={artifacts:[],selectedId:null},Dn=!1,bn=!1,ts=!1,pr=!1,ud=()=>pr||yn.artifacts.some(l=>Xo(o.features?.artifacts,l.artifactType)==="panel"),ia=()=>yn.artifacts.length>0&&!Dn&&ud(),ht={current:null},ol=(l,g)=>{let b=j.getArtifactById(g),v=b?.markdown,T=b?.title||"artifact",R=b?.file,Q=b?.artifactType??"markdown";if(!v){let re=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let se=j.getMessages().find(we=>we.id===re);if(se?.rawContent)try{let we=JSON.parse(se.rawContent);v=we?.props?.markdown,T=we?.props?.title||T,we?.props?.file&&typeof we.props.file=="object"&&(R=we.props.file),!b&&typeof we?.props?.artifactType=="string"&&(Q=we.props.artifactType)}catch{}}}return{markdown:v,title:T,file:R,artifactType:Q}};xe.addEventListener("click",l=>{let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:R,title:Q,file:_}=ol(b,v);if(!R)return;let{filename:G,mime:re,content:pe}=Wu({title:Q,markdown:R,file:_}),se=new Blob([pe],{type:re}),we=URL.createObjectURL(se),Je=document.createElement("a");Je.href=we,Je.download=G,Je.click(),URL.revokeObjectURL(we)}),xe.addEventListener("click",l=>{let b=l.target.closest("[data-artifact-custom-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-artifact-custom-action");if(!v)return;let T=b.closest("[data-artifact-inline]"),R=T?null:b.closest("[data-open-artifact]"),Q=T?T.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,G=(T?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(vt=>vt.id===v);if(!G)return;let{markdown:re,title:pe,file:se,artifactType:we}=ol(b,Q??""),Je={artifactId:Q,title:pe,artifactType:we,markdown:re,file:se};try{Promise.resolve(G.onClick(Je)).catch(()=>{})}catch{}}),xe.addEventListener("click",l=>{let b=l.target.closest("[data-copy-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-copy-artifact");if(!v)return;let T=j.getArtifactById(v),R="";if(T)R=_s(T);else{let{markdown:Q,file:_,artifactType:G}=ol(b,v);G==="markdown"&&(R=_s({id:v,artifactType:"markdown",status:"complete",markdown:Q??"",..._?{file:_}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let Q=oe("check",16,"currentColor",2);Q&&(b.replaceChildren(Q),setTimeout(()=>{let _=oe("copy",16,"currentColor",2);_&&b.replaceChildren(_)},1500))}).catch(()=>{})}),xe.addEventListener("click",l=>{let b=l.target.closest("[data-expand-artifact-inline]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Dn=!1,pr=!0,bn=!0,ts=!0,j.selectArtifact(v),On())}),xe.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let b=g.closest("[data-open-artifact]");if(!b)return;let v=b.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(l.preventDefault(),l.stopPropagation(),Dn=!1,pr=!0,j.selectArtifact(v),On())}),xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let ur=We.composerOverlay,fr=(l,g,b)=>{let v=g.trim();if(!v||!ht.current)return;let T=l.getAttribute("data-tool-call-id")??"",R=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:v,answers:b.structured,values:b.values??(b.source==="multi"?v.split(", "):[v]),isFreeText:R,source:b.source},bubbles:!0,composed:!0})),go(ur,T);let Q=ht.current.getMessages().find(_=>_.toolCall?.id===T);Q?.agentMetadata?.awaitingLocalTool?ht.current.resolveAskUserQuestion(Q,b.structured??v):ht.current.sendMessage(v)},Bo=l=>{let g=ht.current;if(!g)return;let b=l.getAttribute("data-tool-call-id")??"",v=g.getMessages().find(T=>T.toolCall?.id===b);v&&g.persistAskUserQuestionProgress(v,{answers:Da(l,v),currentIndex:mn(l)})},fd=l=>Object.entries(l).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),rl=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=mn(l),b=kr(l);if(g>=b-1)return;let v=ht.current?.getMessages().find(T=>T.toolCall?.id===l.getAttribute("data-tool-call-id"));v&&(Oa(l,v,o,g+1),Bo(l))};ur.addEventListener("click",l=>{let b=l.target.closest("[data-ask-user-action]");if(!b)return;let v=b.closest("[data-persona-ask-sheet-for]");if(!v)return;let T=b.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let R=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),go(ur,R);let Q=ht.current?.getMessages().find(_=>_.toolCall?.id===R);Q?.agentMetadata?.awaitingLocalTool&&(ht.current?.markAskUserQuestionResolved(Q),ht.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(T==="pick"){let R=b.getAttribute("data-option-label");if(!R)return;let Q=v.getAttribute("data-multi-select")==="true",_=fo(v);if(_&&Q){let G=Qo(v)[mn(v)],re=new Set(Array.isArray(G)?G:[]);re.has(R)?re.delete(R):re.add(R),mo(v,Array.from(re)),Bo(v);return}if(_){mo(v,R),Bo(v),rl(v);return}if(Q){let G=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",G?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!G);let re=v.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=$l(v).length===0);return}fr(v,R,{source:"pick",values:[R]});return}if(T==="submit-multi"){let R=$l(v);if(R.length===0)return;fr(v,R.join(", "),{source:"multi",values:R});return}if(T==="open-free-text"){let R=v.querySelector('[data-ask-free-text-row="true"]');R&&(R.classList.remove("persona-hidden"),R.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(T==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(T==="submit-free-text"){let Q=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(fo(v)){mo(v,Q.trim()),Bo(v),rl(v);return}fr(v,Q,{source:"free-text"});return}if(T==="next"||T==="back"){if(!ht.current)return;let R=v.getAttribute("data-tool-call-id")??"",Q=ht.current.getMessages().find(se=>se.toolCall?.id===R);if(!Q)return;let G=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let se=Qo(v)[mn(v)];(typeof se!="string"||se!==G)&&mo(v,G)}let re=T==="next"?1:-1,pe=mn(v)+re;Oa(v,Q,o,pe),Bo(v);return}if(T==="submit-all"){if(!ht.current)return;let R=v.getAttribute("data-tool-call-id")??"",Q=ht.current.getMessages().find(se=>se.toolCall?.id===R);if(!Q)return;let G=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&mo(v,G);let re=Da(v,Q);ht.current.persistAskUserQuestionProgress(Q,{answers:re,currentIndex:mn(v)});let pe=fd(re);fr(v,pe||"(submitted)",{source:"submit-all",structured:re});return}if(T==="skip"){if(!ht.current)return;let R=v.getAttribute("data-tool-call-id")??"",Q=ht.current.getMessages().find(we=>we.toolCall?.id===R);if(!Q)return;let _=fo(v),G=mn(v),re=kr(v),pe=G>=re-1;if(!_){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),go(ur,R),Q.agentMetadata?.awaitingLocalTool&&(ht.current.markAskUserQuestionResolved(Q),ht.current.resolveAskUserQuestion(Q,"(dismissed)"));return}mo(v,"");let se=v.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),pe){let we=Da(v,Q),Je=fd(we);fr(v,Je||"(skipped)",{source:"submit-all",structured:we});return}Oa(v,Q,o,G+1),Bo(v);return}}),ur.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let b=l.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let v=b.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let T=b.value;if(T.trim()){if(fo(v)){mo(v,T.trim()),Bo(v),rl(v);return}fr(v,T,{source:"free-text"})}});let gd=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let b=ur.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),R=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];R&&(l.preventDefault(),R.click())};document.addEventListener("keydown",gd);let to=null,At=null,ns=null,la=null,sl=()=>{},md=!1,ca="",da="";function al(){la?.(),la=null}let hd=()=>{if(!to||!At)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,b=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){At.style.removeProperty("position"),At.style.removeProperty("left"),At.style.removeProperty("top"),At.style.removeProperty("bottom"),At.style.removeProperty("width"),At.style.removeProperty("z-index");return}let v=to.firstElementChild;if(!v||v===At)return;let T=10;At.style.position="absolute",At.style.top="0",At.style.bottom="0",At.style.width=`${T}px`,At.style.zIndex="5";let R=Ic(to,g),Q=v.offsetWidth+R/2-T/2;At.style.left=`${Math.max(0,Q)}px`},pa=()=>{},Kg=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>b?!1:A||Wt(o)},ua=()=>!Qt(o)||!ia()||e.classList.contains("persona-artifact-narrow-host")||Kg()||(e.ownerDocument.defaultView??window).innerWidth<fv?"none":Rc(o)?"detached":"welded",On=()=>{if(!Ze||!Qt(o))return;Xs(e,o),Qs(e,o),pa();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let b=ia();Ze.setVisible(b),Ze.update(yn),Dn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),bn=!1,ts=!1):yn.artifacts.length>0&&ud()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),bn=!1,ts=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(v),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!ts&&(bn=!1),bn!==md){let R=Ze.element;bn?(ca=R.style.width,da=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(ca&&(R.style.width=ca),da&&(R.style.maxWidth=da),ca="",da=""),md=bn}e.classList.toggle("persona-artifact-expanded",bn),Ze.setExpanded(bn);let T=ua();T!==es&&(es=T,Zr()),sl()};if(Qt(o)){ye.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),Ze=Ff(o,{onSelect:b=>ht.current?.selectArtifact(b),onDismiss:()=>{Dn=!0,On()},onToggleExpand:()=>{let b=!bn,v=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:b})!==!0&&(bn=b,b||(ts=!1),On())}}),Ze.element.classList.add("persona-hidden"),to=g,g.appendChild(l),g.appendChild(Ze.element),Ze.backdrop&&ye.appendChild(Ze.backdrop),ye.appendChild(g),sl=()=>{if(!to||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ns?.(),ns=null,al(),At&&(At.remove(),At=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!At){let v=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let T=e.ownerDocument,R=T.defaultView??window,Q=_=>{if(!Ze||_.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;_.preventDefault(),al();let G=_.clientX,re=Ze.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,se=Je=>{let vt=to.getBoundingClientRect().width,lt=e.classList.contains("persona-artifact-welded-split"),Vt=Ic(to,R),Ot=lt?0:v.getBoundingClientRect().width||6,H=re-(Je.clientX-G),je=Uf(H,vt,Vt,Ot,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ze.element.style.width=`${je}px`,Ze.element.style.maxWidth="none",hd()},we=()=>{T.removeEventListener("pointermove",se),T.removeEventListener("pointerup",we),T.removeEventListener("pointercancel",we),la=null;try{v.releasePointerCapture(_.pointerId)}catch{}};la=we,T.addEventListener("pointermove",se),T.addEventListener("pointerup",we),T.addEventListener("pointercancel",we);try{v.setPointerCapture(_.pointerId)}catch{}};v.addEventListener("pointerdown",Q),At=v,to.insertBefore(v,Ze.element),ns=()=>{v.removeEventListener("pointerdown",Q)}}if(At){let v=ia();At.classList.toggle("persona-hidden",!v),hd()}},pa=()=>{if(!A||!Ze||(o.launcher?.sidebarMode??!1)||Wt(o)&&tn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(T&&v.innerWidth<=R||!jf(o,A))return;let Q=o.launcher?.width??o.launcherWidth??cn,_=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ia()?(ye.style.width=_,ye.style.maxWidth=_):(ye.style.width=Q,ye.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(Yr=new ResizeObserver(()=>{On()}),Yr.observe(ye))}else ye.appendChild(ge);Y()&&ct&&(We.peekBanner&&ct.appendChild(We.peekBanner),ct.appendChild(q)),e.appendChild(ke),ct&&e.appendChild(ct);let fa=()=>{if(Y()){ye.style.width="100%",ye.style.maxWidth="100%";let It=o.launcher?.composerBar??{},Zt=ke.dataset.state==="expanded",Ea=It.expandedSize??"anchored";if(!(Zt&&Ea!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let hs=o.theme?.components?.panel,Ma=Co(o),Cr=($n,Vo)=>$n==null||$n===""?Vo:Jt(Ma,$n)??$n,ys="1px solid var(--persona-border)",Rl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",qo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=Cr(hs?.border,ys),ge.style.borderRadius=Cr(hs?.borderRadius,qo),ge.style.boxShadow=Cr(hs?.shadow,Rl),ge.style.overflow="hidden";return}let l=Wt(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,T=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,Q=Co(o),_=(It,Zt)=>It==null||It===""?Zt:Jt(Q,It)??It,G=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,se=G.innerWidth<=pe,we=re&&se&&A,Je=l&&re&&se,vt=o.launcher?.position??"bottom-left",lt=vt==="bottom-left"||vt==="top-left",Vt=o.launcher?.zIndex??zt,Ot="var(--persona-panel-border, 1px solid var(--persona-border))",H="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",je="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Se=T&&!we&&!Je;Se?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ue=Se?Ot:g||we?"none":Ot,kt=Se?H:we?"none":g?lt?"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))":v?"none":H;l&&!we&&!Se&&(kt="none",Ue="none");let ft=Se?je:g||we?"0":je,Tt=_(R?.border,Ue),xt=_(R?.shadow,kt),jt=_(R?.borderRadius,ft),Uo=ua(),gt=Uo==="detached",ue=Uo==="welded";e.classList.toggle("persona-artifact-detached-split",gt),e.classList.toggle("persona-artifact-welded-split",ue);let Et="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)))))",at=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Qt(o)&&Rc(o)&&v&&!l;e.classList.toggle("persona-artifact-chat-flush",at);let Ke=gt||at?"none":xt,et=gt?Ot:ue?"none":Tt,Rt=gt?je:jt;at&&(et="none",Rt="0");let De=R?.borderRadius!=null&&R.borderRadius!=="",tt=at&&!De?"0":jt,sn=ce.scrollTop;e.style.cssText="",ke.style.cssText="",ye.style.cssText="",ge.style.cssText="",ce.style.cssText="",q.style.cssText="",Ae&&(ce.style.display="none");let zo=()=>{if(sn<=0)return;(ce.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ce.scrollTop===sn)return;let Zt=ce.scrollHeight-ce.clientHeight;Zt<=0||(ce.scrollTop=Math.min(sn,Zt))})};if(we){ke.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"),ke.style.cssText=`
48
+ `,w.addEventListener("click",()=>{u=N,P.forEach((q,V)=>{let Y=V<N;q.classList.toggle("selected",Y),q.setAttribute("aria-checked",V===N-1?"true":"false")})}),P.push(w),M.appendChild(w)}y.appendChild(M);let I=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),N.appendChild(I),y.appendChild(N)}let A=document.createElement("div");A.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{n?.(),c.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=a,$.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let N=I?.value.trim()||void 0;await t(u,N),c.remove()}catch(N){$.disabled=!1,$.textContent=a,console.error("[CSAT Feedback] Failed to submit:",N)}}),A.appendChild(W),A.appendChild($),y.appendChild(A),c.appendChild(y),c}function Ui(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 y=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,h.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,h.appendChild(M),f.appendChild(h);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 I=document.createElement("div");I.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=d;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=c,I.appendChild(A),I.appendChild(W);let $=document.createElement("div");$.className="persona-feedback-numbers";let N=[];for(let O=0;O<=10;O++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${O} out of 10`),U.textContent=String(O),U.dataset.rating=String(O),O<=6?U.classList.add("persona-feedback-detractor"):O<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{y=O,N.forEach((me,ve)=>{me.classList.toggle("selected",ve===O),me.setAttribute("aria-checked",ve===O?"true":"false")})}),N.push(U),$.appendChild(U)}P.appendChild(I),P.appendChild($),f.appendChild(P);let w=null;if(p){let O=document.createElement("div");O.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"),O.appendChild(w),f.appendChild(O)}let q=document.createElement("div");q.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(y===null){$.classList.add("persona-feedback-shake"),setTimeout(()=>$.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(y,O),u.remove()}catch(O){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),q.appendChild(V),q.appendChild(Y),f.appendChild(q),u.appendChild(f),u}var Gr="persona-chat-history",hv=30*1e3,yv=641,bv={"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 vv(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=bv[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 zi(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 xv(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 Cv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Oc=e=>!e||typeof e!="object"?{}:{...e},Zf=e=>e.map(t=>({...t,streaming:!1})),eg=(e,t,n)=>{let o=e?.markdown?Jo(e.markdown):null,r=Tr(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=jn()!==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?Ep(a):a,u=o(c);d=r&&p?r(u):u}else d=Rn(a);return d}};function tg(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 wv=(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},Av=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:wv(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),qi=(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=Br(t),r=Zs.getForInstance(o.plugins),{plugin:s,teardown:a}=Hf();o.components&&En.registerAll(o.components);let i=Gf(),d=o.persistState===!1?null:o.storageAdapter??Ni(),c={},u=null,y=!1,f=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:x}=g;return x&&(y=!0),b}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(g=>f(g??{messages:[],metadata:{}}));else{let b=f(l??{messages:[],metadata:{}});b.metadata&&(c=Oc(b.metadata)),b.messages?.length&&(o={...o,initialMessages:b.messages}),b.artifacts?.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=f({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let h=()=>c,C=l=>{c=l({...c})??{},hl()},M=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ea],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[cr.message,cr.messageAndClick],I=ta({parsers:M,handlers:P,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});I.syncFromMetadata();let A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,$=o.autoFocusInput??!1,N=W,w=A,q=o.layout?.header?.layout,V=!1,Y=()=>Lo(o),O=()=>A||Y(),U=Y()?!1:A?W:!0,me=!1,ve=null,Me=()=>{me=!0,ve&&clearTimeout(ve),ve=setTimeout(()=>{me&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),me=!1)},1e4)},Oe=eg(o,I,Me),ie=o.features?.showReasoning??!0,xe=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,ce=o.features?.scrollToBottom??{},ee=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ue=Z?new Js(he):null,Re=o.features?.eventStream?.maxEvents??2e3,Ne=Z?new Gs(Re,ue):null,je=Z?new Xs:null,Be=null,Ue=!1,Xe=null,ke=0;ue?.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),j?.isClientTokenMode()&&j.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),j?.isClientTokenMode()&&j.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},Ie=o.statusIndicator??{},Ct=l=>l==="idle"?Ie.idleText??Bt.idle:l==="connecting"?Ie.connectingText??Bt.connecting:l==="connected"?Ie.connectedText??Bt.connected:l==="error"?Ie.errorText??Bt.error:l==="paused"?Ie.pausedText??Bt.paused:l==="resuming"?Ie.resumingText??Bt.resuming:Bt[l];function yt(l,g,b,x){if(x==="idle"&&b.idleLink){l.textContent="";let E=document.createElement("a");E.href=b.idleLink,E.target="_blank",E.rel="noopener noreferrer",E.textContent=g,E.style.color="inherit",E.style.textDecoration="none",l.appendChild(E)}else l.textContent=g}let pt=vf({config:o,showClose:O()}),{wrapper:We,panel:ye,pillRoot:Ze}=pt.shell,Le=pt.panelElements,{container:ge,body:le,messagesWrapper:Ce,suggestions:wt,textarea:be,sendButton:fe,sendButtonWrapper:hn,composerForm:Q,statusText:k,introTitle:F,introSubtitle:v,closeButton:S,iconHolder:L,headerTitle:B,headerSubtitle:K,header:D,footer:z,actionsRow:re,rightActions:Qe}=Le,Te=Le.leftActions,ct=Le.setSendButtonMode,G=Le.micButton,ze=Le.micButtonWrapper,Ee=Le.attachmentButton,He=Le.attachmentButtonWrapper,Pe=Le.attachmentInput,tt=Le.attachmentPreviewsContainer;ge.classList.add("persona-relative"),le.classList.add("persona-relative");let Ro=12,Io=()=>ce.label??"",el=()=>ce.iconName??"arrow-down",sa=()=>ce.enabled!==!1,Qt=()=>ee.mode??"anchor-top",Yn=()=>Qt()==="follow"||Qt()==="anchor-top"&&os,ed=()=>ee.anchorTopOffset??16,zg=()=>ee.restorePosition??"bottom",td=()=>ee.pauseOnInteraction===!0,nd=()=>ee.showActivityWhilePinned!==!1,od=()=>ee.announce===!0,Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let Jr=m("span","persona-flex persona-items-center"),tl=m("span",""),Wo=m("span","");Wo.setAttribute("data-persona-scroll-to-bottom-count",""),Wo.style.display="none",Wt.append(Jr,tl,Wo),ge.appendChild(Wt);let Zn=m("div","persona-stream-anchor-spacer");Zn.setAttribute("aria-hidden","true"),Zn.setAttribute("data-persona-anchor-spacer",""),Zn.style.flexShrink="0",Zn.style.pointerEvents="none",Zn.style.height="0px",le.appendChild(Zn);let Ho=m("div","persona-sr-only");Ho.setAttribute("aria-live","polite"),Ho.setAttribute("aria-atomic","true"),Ho.setAttribute("role","status"),Ho.setAttribute("data-persona-live-region",""),Object.assign(Ho.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(Ho);let Xr=null,aa=null,rd=l=>{!od()||!l||(aa=l,Xr===null&&(Xr=setTimeout(()=>{Xr=null,aa&&od()&&(Ho.textContent=aa),aa=null},400)))},dr=()=>{let g=z.style.display==="none"?0:z.offsetHeight;Wt.style.bottom=`${g+Ro}px`};dr();let sd=()=>{let l=!!Io();Wt.setAttribute("aria-label",Io()||"Jump to latest"),Wt.title=Io(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Jr.innerHTML="";let g=ne(el(),"14px","currentColor",2);g?(Jr.appendChild(g),Jr.style.display=""):Jr.style.display="none",tl.textContent=Io(),tl.style.display=l?"":"none"};sd();let kt=null,tn=null,ad=null,id=r.find(l=>l.renderHeader);if(id?.renderHeader){let l=id.renderHeader({config:o,defaultRenderer:()=>{let g=Xn({config:o,showClose:O()});return rr(ge,g,o),g.header},onClose:()=>ht(!1,"user")});if(l){let g=ge.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),D=l,pt.header.element=l)}}let nl=()=>{if(!Ne)return;if(Ue=!0,!Be&&Ne&&(Be=Ff({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Qr(),config:o,plugins:r,getThroughput:()=>je?.getMetric()??{status:"idle"}})),Be&&(le.style.display="none",z.parentNode?.insertBefore(Be.element,z),Be.update()),it){it.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(b=>b&&it.classList.add(b))}let l=()=>{if(!Ue)return;let g=Date.now();g-ke>=200&&(Be?.update(),ke=g),Xe=requestAnimationFrame(l)};ke=0,Xe=requestAnimationFrame(l),on(),i.emit("eventStream:opened",{timestamp:Date.now()})},Qr=()=>{if(Ue){if(Ue=!1,Be&&Be.element.remove(),le.style.display="",it){it.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&it.classList.remove(g))}Xe!==null&&(cancelAnimationFrame(Xe),Xe=null),on(),i.emit("eventStream:closed",{timestamp:Date.now()})}},it=null;if(Z){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");it=m("button",g),it.style.width="28px",it.style.height="28px",it.style.color=Jt.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let b=ne("activity","18px","currentColor",1.5);b&&it.appendChild(b);let x=Le.clearChatButtonWrapper,E=Le.closeButtonWrapper,R=x||E;R&&R.parentNode===D?D.insertBefore(it,R):D.appendChild(it),it.addEventListener("click",()=>{Ue?Qr():nl()})}let qg=l=>{let g=o.attachments;if(!g?.enabled)return;let b=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!b){b=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let E=l.querySelector("[data-persona-composer-form]");E?.parentNode?E.parentNode.insertBefore(b,E):l.insertBefore(b,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let E=m("input");E.type="file",E.setAttribute("data-persona-composer-attachment-input",""),E.accept=(g.allowedTypes??Kn).join(","),E.multiple=(g.maxFiles??4)>1,E.style.display="none",E.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(E)}},ld=r.find(l=>l.renderComposer);if(ld?.renderComposer){let l=o.composer,g=ld.renderComposer({config:o,defaultRenderer:()=>jr({config:o}).footer,onSubmit:b=>{if(!j||j.isStreaming())return;let x=b.trim(),E=kt?.hasAttachments()??!1;if(!x&&!E)return;Od();let R;E&&(R=[],R.push(...kt.getContentParts()),x&&R.push(bo(x))),j.sendMessage(x,{contentParts:R}),E&&kt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Pe?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{ad?.()}:void 0});g&&(pt.replaceComposer(g),z=pt.composer.footer)}let Vg=l=>{let g=(...de)=>{for(let ae of de){let Ae=l.querySelector(ae);if(Ae)return Ae}return null},b=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),X=l.querySelector("[data-persona-composer-status]");b&&(Q=b),x&&(be=x),E&&(fe=E),R&&(G=R,ze=R.parentElement),X&&(k=X);let _=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(wt=_);let J=g("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Ee=J,He=J.parentElement),Pe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),tt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(re=se),Te=g(".persona-widget-composer__left-actions")};qg(z),Vg(z);let eo=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(eo&&(Ce.style.maxWidth=eo,Ce.style.marginLeft="auto",Ce.style.marginRight="auto",Ce.style.width="100%"),eo&&Q&&!Y()&&(Q.style.maxWidth=eo,Q.style.marginLeft="auto",Q.style.marginRight="auto"),eo&&wt&&!Y()&&(wt.style.maxWidth=eo,wt.style.marginLeft="auto",wt.style.marginRight="auto"),eo&&tt&&!Y()&&(tt.style.maxWidth=eo,tt.style.marginLeft="auto",tt.style.marginRight="auto"),o.attachments?.enabled&&Pe&&tt){kt=tr.fromConfig(o.attachments),kt.setPreviewsContainer(tt),Pe.addEventListener("change",b=>{let x=b.target;kt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,g=tg(l);ge.appendChild(g)}let Kg=()=>tn?.prefetch();if(o.contextMentions?.enabled&&be&&(tn=Mu({config:o,textarea:be,anchor:Q??be,getMessages:()=>j.getMessages(),liveRegionHost:ge}),tn)){let l=be;l.parentElement?.insertBefore(tn.contextRow,l);let g=tn.affordanceButtons;for(let b=g.length-1;b>=0;b--){let x=g[b];Te?Te.insertBefore(x,Te.firstChild):Q?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ce;case"footer-top":return wt;case"composer":return Q;case"footer-bottom":return k;default:return null}},b=(x,E)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")D.insertBefore(E,D.firstChild);else if(x==="header-right")D.appendChild(E);else{let R=D.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(E,R.nextSibling):D.appendChild(E)}break;case"body-top":{let R=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(E):le.insertBefore(E,le.firstChild);break}case"body-bottom":le.appendChild(E);break;case"footer-top":wt.replaceWith(E);break;case"footer-bottom":k.replaceWith(E);break;default:break}};for(let[x,E]of Object.entries(l))if(E)try{let R=E({config:o,defaultContent:()=>g(x)});R&&b(x,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,R)}})();let cd=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let x=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let E=x.getAttribute("data-message-id");if(!E)return;let R=b.getAttribute("data-bubble-type");if(R==="reasoning")zr.has(E)?zr.delete(E):zr.add(E),Tf(E,x);else if(R==="tool")qr.has(E)?qr.delete(E):qr.add(E),Ef(E,x,o);else if(R==="approval"){let _=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=ar.get(E)??_;ar.set(E,!J),Pf(E,x,o)}No.delete(E)};Ce.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cd(l))}),Ce.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cd(l))}),Ce.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let b=Ce.getRootNode(),x=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let E=x.toString(),R=Yu(E);!R||R===E||(g.setData("text/plain",R),l.preventDefault())});let ol=new Map,dd=null,pd="idle",Gg={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Jg=(l,g)=>{let{icon:b,label:x}=Gg[g];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let E=ne(b,14,"currentColor",2);E&&(l.innerHTML="",l.appendChild(E))},ud=()=>{Ce.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Jg(g,x&&x===dd?pd:"idle")})};Ce.addEventListener("click",l=>{let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.closest("[data-actions-for]");if(!x)return;let E=x.getAttribute("data-actions-for");if(!E)return;let R=b.getAttribute("data-action");if(R==="copy"){let _=j.getMessages().find(J=>J.id===E);if(_&&oe.onCopy){let J=_.content||"";navigator.clipboard.writeText(J).then(()=>{b.classList.add("persona-message-action-success");let se=ne("check",14,"currentColor",2);se&&(b.innerHTML="",b.appendChild(se)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let de=ne("copy",14,"currentColor",2);de&&(b.innerHTML="",b.appendChild(de))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),oe.onCopy(_)}}else if(R==="read-aloud")j.toggleReadAloud(E);else if(R==="upvote"||R==="downvote"){let _=(ol.get(E)??null)===R,J=R==="upvote"?"thumbs-up":"thumbs-down";if(_){ol.delete(E),b.classList.remove("persona-message-action-active");let se=ne(J,14,"currentColor",2);se&&(b.innerHTML="",b.appendChild(se))}else{let se=R==="upvote"?"downvote":"upvote",de=x.querySelector(`[data-action="${se}"]`);if(de){de.classList.remove("persona-message-action-active");let lt=ne(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);lt&&(de.innerHTML="",de.appendChild(lt))}ol.set(E,R),b.classList.add("persona-message-action-active");let ae=ne(J,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(ae)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Je=j.getMessages().find(bt=>bt.id===E);Je&&oe.onFeedback&&oe.onFeedback({type:R,messageId:Je.id,message:Je})}}}),Ce.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.closest(".persona-approval-bubble");if(!x)return;let E=x.getAttribute("data-message-id");if(!E)return;let R=b.getAttribute("data-approval-action");if(!R)return;let X=R==="approve"?"approved":"denied",J=j.getMessages().find(de=>de.id===E);if(!J?.approval)return;let se=x.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?j.resolveWebMcpApproval(E,X):j.resolveApproval(J.approval,X)});let nt=null,Yr=null,Zr=()=>{},es="none",ia=null,yn={artifacts:[],selectedId:null},Dn=!1,bn=!1,ts=!1,pr=!1,fd=()=>pr||yn.artifacts.some(l=>Xo(o.features?.artifacts,l.artifactType)==="panel"),la=()=>yn.artifacts.length>0&&!Dn&&fd(),mt={current:null},rl=(l,g)=>{let b=j.getArtifactById(g),x=b?.markdown,E=b?.title||"artifact",R=b?.file,X=b?.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 ae=j.getMessages().find(Ae=>Ae.id===se);if(ae?.rawContent)try{let Ae=JSON.parse(ae.rawContent);x=Ae?.props?.markdown,E=Ae?.props?.title||E,Ae?.props?.file&&typeof Ae.props.file=="object"&&(R=Ae.props.file),!b&&typeof Ae?.props?.artifactType=="string"&&(X=Ae.props.artifactType)}catch{}}}return{markdown:x,title:E,file:R,artifactType:X}};Ce.addEventListener("click",l=>{let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:R,title:X,file:_}=rl(b,x);if(!R)return;let{filename:J,mime:se,content:de}=Hu({title:X,markdown:R,file:_}),ae=new Blob([de],{type:se}),Ae=URL.createObjectURL(ae),Je=document.createElement("a");Je.href=Ae,Je.download=J,Je.click(),URL.revokeObjectURL(Ae)}),Ce.addEventListener("click",l=>{let b=l.target.closest("[data-artifact-custom-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-artifact-custom-action");if(!x)return;let E=b.closest("[data-artifact-inline]"),R=E?null:b.closest("[data-open-artifact]"),X=E?E.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,J=(E?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(bt=>bt.id===x);if(!J)return;let{markdown:se,title:de,file:ae,artifactType:Ae}=rl(b,X??""),Je={artifactId:X,title:de,artifactType:Ae,markdown:se,file:ae};try{Promise.resolve(J.onClick(Je)).catch(()=>{})}catch{}}),Ce.addEventListener("click",l=>{let b=l.target.closest("[data-copy-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-copy-artifact");if(!x)return;let E=j.getArtifactById(x),R="";if(E)R=$s(E);else{let{markdown:X,file:_,artifactType:J}=rl(b,x);J==="markdown"&&(R=$s({id:x,artifactType:"markdown",status:"complete",markdown:X??"",..._?{file:_}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let X=ne("check",16,"currentColor",2);X&&(b.replaceChildren(X),setTimeout(()=>{let _=ne("copy",16,"currentColor",2);_&&b.replaceChildren(_)},1500))}).catch(()=>{})}),Ce.addEventListener("click",l=>{let b=l.target.closest("[data-expand-artifact-inline]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Dn=!1,pr=!0,bn=!0,ts=!0,j.selectArtifact(x),On())}),Ce.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let b=g.closest("[data-open-artifact]");if(!b)return;let x=b.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),Dn=!1,pr=!0,j.selectArtifact(x),On())}),Ce.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let ur=Le.composerOverlay,fr=(l,g,b)=>{let x=g.trim();if(!x||!mt.current)return;let E=l.getAttribute("data-tool-call-id")??"",R=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:x,answers:b.structured,values:b.values??(b.source==="multi"?x.split(", "):[x]),isFreeText:R,source:b.source},bubbles:!0,composed:!0})),go(ur,E);let X=mt.current.getMessages().find(_=>_.toolCall?.id===E);X?.agentMetadata?.awaitingLocalTool?mt.current.resolveAskUserQuestion(X,b.structured??x):mt.current.sendMessage(x)},Bo=l=>{let g=mt.current;if(!g)return;let b=l.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(E=>E.toolCall?.id===b);x&&g.persistAskUserQuestionProgress(x,{answers:Oa(l,x),currentIndex:gn(l)})},gd=l=>Object.entries(l).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),sl=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=gn(l),b=kr(l);if(g>=b-1)return;let x=mt.current?.getMessages().find(E=>E.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(Na(l,x,o,g+1),Bo(l))};ur.addEventListener("click",l=>{let b=l.target.closest("[data-ask-user-action]");if(!b)return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;let E=b.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),E==="dismiss"){let R=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),go(ur,R);let X=mt.current?.getMessages().find(_=>_.toolCall?.id===R);X?.agentMetadata?.awaitingLocalTool&&(mt.current?.markAskUserQuestionResolved(X),mt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(E==="pick"){let R=b.getAttribute("data-option-label");if(!R)return;let X=x.getAttribute("data-multi-select")==="true",_=fo(x);if(_&&X){let J=Qo(x)[gn(x)],se=new Set(Array.isArray(J)?J:[]);se.has(R)?se.delete(R):se.add(R),mo(x,Array.from(se)),Bo(x);return}if(_){mo(x,R),Bo(x),sl(x);return}if(X){let J=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",J?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!J);let se=x.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=jl(x).length===0);return}fr(x,R,{source:"pick",values:[R]});return}if(E==="submit-multi"){let R=jl(x);if(R.length===0)return;fr(x,R.join(", "),{source:"multi",values:R});return}if(E==="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(E==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(E==="submit-free-text"){let X=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(fo(x)){mo(x,X.trim()),Bo(x),sl(x);return}fr(x,X,{source:"free-text"});return}if(E==="next"||E==="back"){if(!mt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=mt.current.getMessages().find(ae=>ae.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ae=Qo(x)[gn(x)];(typeof ae!="string"||ae!==J)&&mo(x,J)}let se=E==="next"?1:-1,de=gn(x)+se;Na(x,X,o,de),Bo(x);return}if(E==="submit-all"){if(!mt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=mt.current.getMessages().find(ae=>ae.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&mo(x,J);let se=Oa(x,X);mt.current.persistAskUserQuestionProgress(X,{answers:se,currentIndex:gn(x)});let de=gd(se);fr(x,de||"(submitted)",{source:"submit-all",structured:se});return}if(E==="skip"){if(!mt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=mt.current.getMessages().find(Ae=>Ae.toolCall?.id===R);if(!X)return;let _=fo(x),J=gn(x),se=kr(x),de=J>=se-1;if(!_){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),go(ur,R),X.agentMetadata?.awaitingLocalTool&&(mt.current.markAskUserQuestionResolved(X),mt.current.resolveAskUserQuestion(X,"(dismissed)"));return}mo(x,"");let ae=x.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),de){let Ae=Oa(x,X),Je=gd(Ae);fr(x,Je||"(skipped)",{source:"submit-all",structured:Ae});return}Na(x,X,o,J+1),Bo(x);return}}),ur.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let b=l.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let E=b.value;if(E.trim()){if(fo(x)){mo(x,E.trim()),Bo(x),sl(x);return}fr(x,E,{source:"free-text"})}});let md=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let b=ur.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),R=b.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",md);let to=null,At=null,ns=null,ca=null,al=()=>{},hd=!1,da="",pa="";function il(){ca?.(),ca=null}let yd=()=>{if(!to||!At)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,b=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){At.style.removeProperty("position"),At.style.removeProperty("left"),At.style.removeProperty("top"),At.style.removeProperty("bottom"),At.style.removeProperty("width"),At.style.removeProperty("z-index");return}let x=to.firstElementChild;if(!x||x===At)return;let E=10;At.style.position="absolute",At.style.top="0",At.style.bottom="0",At.style.width=`${E}px`,At.style.zIndex="5";let R=Wc(to,g),X=x.offsetWidth+R/2-E/2;At.style.left=`${Math.max(0,X)}px`},ua=()=>{},Xg=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>b?!1:A||It(o)},fa=()=>!Xt(o)||!la()||e.classList.contains("persona-artifact-narrow-host")||Xg()||(e.ownerDocument.defaultView??window).innerWidth<yv?"none":Ic(o)?"detached":"welded",On=()=>{if(!nt||!Xt(o))return;Qs(e,o),Ys(e,o),ua();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let b=la();nt.setVisible(b),nt.update(yn),Dn?(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),bn=!1,ts=!1):yn.artifacts.length>0&&fd()?(nt.element.classList.remove("persona-hidden"),nt.setMobileOpen(!0)):(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),bn=!1,ts=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(nt.setExpandToggleVisible(x),nt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),nt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),nt.setTabFade(o.features?.artifacts?.layout?.tabFade),nt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!ts&&(bn=!1),bn!==hd){let R=nt.element;bn?(da=R.style.width,pa=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(da&&(R.style.width=da),pa&&(R.style.maxWidth=pa),da="",pa=""),hd=bn}e.classList.toggle("persona-artifact-expanded",bn),nt.setExpanded(bn);let E=fa();E!==es&&(es=E,Zr()),al()};if(Xt(o)){ye.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),nt=_f(o,{onSelect:b=>mt.current?.selectArtifact(b),onDismiss:()=>{Dn=!0,On()},onToggleExpand:()=>{let b=!bn,x=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:b})!==!0&&(bn=b,b||(ts=!1),On())}}),nt.element.classList.add("persona-hidden"),to=g,g.appendChild(l),g.appendChild(nt.element),nt.backdrop&&ye.appendChild(nt.backdrop),ye.appendChild(g),al=()=>{if(!to||!nt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ns?.(),ns=null,il(),At&&(At.remove(),At=null),nt.element.style.removeProperty("width"),nt.element.style.removeProperty("maxWidth");return}if(!At){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 E=e.ownerDocument,R=E.defaultView??window,X=_=>{if(!nt||_.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;_.preventDefault(),il();let J=_.clientX,se=nt.element.getBoundingClientRect().width,de=o.features?.artifacts?.layout,ae=Je=>{let bt=to.getBoundingClientRect().width,lt=e.classList.contains("persona-artifact-welded-split"),Vt=Wc(to,R),Dt=lt?0:x.getBoundingClientRect().width||6,H=se-(Je.clientX-J),_e=zf(H,bt,Vt,Dt,de?.resizableMinWidth,de?.resizableMaxWidth);nt.element.style.width=`${_e}px`,nt.element.style.maxWidth="none",yd()},Ae=()=>{E.removeEventListener("pointermove",ae),E.removeEventListener("pointerup",Ae),E.removeEventListener("pointercancel",Ae),ca=null;try{x.releasePointerCapture(_.pointerId)}catch{}};ca=Ae,E.addEventListener("pointermove",ae),E.addEventListener("pointerup",Ae),E.addEventListener("pointercancel",Ae);try{x.setPointerCapture(_.pointerId)}catch{}};x.addEventListener("pointerdown",X),At=x,to.insertBefore(x,nt.element),ns=()=>{x.removeEventListener("pointerdown",X)}}if(At){let x=la();At.classList.toggle("persona-hidden",!x),yd()}},ua=()=>{if(!A||!nt||(o.launcher?.sidebarMode??!1)||It(o)&&en(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,E=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(E&&x.innerWidth<=R||!Uf(o,A))return;let X=o.launcher?.width??o.launcherWidth??ln,_=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";la()?(ye.style.width=_,ye.style.maxWidth=_):(ye.style.width=X,ye.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Yr=new ResizeObserver(()=>{On()}),Yr.observe(ye))}else ye.appendChild(ge);Y()&&Ze&&(Le.peekBanner&&Ze.appendChild(Le.peekBanner),Ze.appendChild(z)),e.appendChild(We),Ze&&e.appendChild(Ze);let ga=()=>{if(Y()){ye.style.width="100%",ye.style.maxWidth="100%";let Rt=o.launcher?.composerBar??{},Yt=We.dataset.state==="expanded",Ma=Rt.expandedSize??"anchored";if(!(Yt&&Ma!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let hs=o.theme?.components?.panel,ka=Co(o),Cr=($n,Vo)=>$n==null||$n===""?Vo:Gt(ka,$n)??$n,ys="1px solid var(--persona-border)",Il="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",qo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=Cr(hs?.border,ys),ge.style.borderRadius=Cr(hs?.borderRadius,qo),ge.style.boxShadow=Cr(hs?.shadow,Il),ge.style.overflow="hidden";return}let l=It(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,E=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,X=Co(o),_=(Rt,Yt)=>Rt==null||Rt===""?Yt:Gt(X,Rt)??Rt,J=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,de=o.launcher?.mobileBreakpoint??640,ae=J.innerWidth<=de,Ae=se&&ae&&A,Je=l&&se&&ae,bt=o.launcher?.position??"bottom-left",lt=bt==="bottom-left"||bt==="top-left",Vt=o.launcher?.zIndex??zt,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",H="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_e="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Se=E&&!Ae&&!Je;Se?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let $e=Se?Dt:g||Ae?"none":Dt,Mt=Se?H:Ae?"none":g?lt?"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":H;l&&!Ae&&!Se&&(Mt="none",$e="none");let ut=Se?_e:g||Ae?"0":_e,Tt=_(R?.border,$e),xt=_(R?.shadow,Mt),jt=_(R?.borderRadius,ut),Uo=fa(),ft=Uo==="detached",pe=Uo==="welded";e.classList.toggle("persona-artifact-detached-split",ft),e.classList.toggle("persona-artifact-welded-split",pe);let Et="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)&&Ic(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",st);let Ve=ft||st?"none":xt,ot=ft?Dt:pe?"none":Tt,Pt=ft?_e:jt;st&&(ot="none",Pt="0");let De=R?.borderRadius!=null&&R.borderRadius!=="",rt=st&&!De?"0":jt,rn=le.scrollTop;e.style.cssText="",We.style.cssText="",ye.style.cssText="",ge.style.cssText="",le.style.cssText="",z.style.cssText="",Ue&&(le.style.display="none");let zo=()=>{if(rn<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===rn)return;let Yt=le.scrollHeight-le.clientHeight;Yt<=0||(le.scrollTop=Math.min(rn,Yt))})};if(Ae){We.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"),We.style.cssText=`
49
49
  position: fixed !important;
50
50
  inset: 0 !important;
51
51
  width: 100% !important;
@@ -81,11 +81,11 @@ _Details: ${n.message}_`:o}var Ws=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",q.style.flexShrink="0",V=!0,zo();return}let Ta=o?.launcher?.width??o?.launcherWidth??cn;if(!g&&!l)v&&b?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=Ta,ye.style.maxWidth=Ta);else if(l)if(tn(o).reveal==="emerge"&&!T){let Zt=tn(o).width;ye.style.width=Zt,ye.style.maxWidth=Zt}else ye.style.width="100%",ye.style.maxWidth="100%";if(pa(),ye.style.boxShadow=Ke,ye.style.borderRadius=tt,gt?ye.style.border="none":ue&&(ye.style.border=Tt),ge.style.border=et,ge.style.borderRadius=Rt,ge.style.boxShadow=gt&&!at?Et:"",at&&(ge.style.background="transparent",ce.style.background="transparent",q.style.background="transparent",q.style.borderTop="none"),ue){let It=o.features?.artifacts?.layout;aa=It?.unifiedSplitOuterRadius?.trim()||It?.paneBorderRadius?.trim()||jt}else aa=null;if(l&&!we&&!Se&&!gt&&!ue&&R?.border===void 0&&(ge.style.border="none",tn(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),l&&!we&&ue&&R?.border===void 0&&(tn(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.maxHeight="100%",ke.style.height="100%",v&&(ke.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",gt||(ye.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",q.style.flexShrink="0"),v&&(Se||gt||at)&&!l&&(at||(ke.style.padding="var(--persona-panel-inset)"),ke.style.background="var(--persona-panel-canvas-bg)"),ke.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!v&&!l&&(Mn[vt]??Mn["bottom-right"]).split(" ").forEach(Zt=>ke.classList.add(Zt)),g){let It=o.launcher?.sidebarWidth??"420px";T?ke.style.cssText=`
84
+ `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",z.style.flexShrink="0",V=!0,zo();return}let Ea=o?.launcher?.width??o?.launcherWidth??ln;if(!g&&!l)x&&b?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=Ea,ye.style.maxWidth=Ea);else if(l)if(en(o).reveal==="emerge"&&!E){let Yt=en(o).width;ye.style.width=Yt,ye.style.maxWidth=Yt}else ye.style.width="100%",ye.style.maxWidth="100%";if(ua(),ye.style.boxShadow=Ve,ye.style.borderRadius=rt,ft?ye.style.border="none":pe&&(ye.style.border=Tt),ge.style.border=ot,ge.style.borderRadius=Pt,ge.style.boxShadow=ft&&!st?Et:"",st&&(ge.style.background="transparent",le.style.background="transparent",z.style.background="transparent",z.style.borderTop="none"),pe){let Rt=o.features?.artifacts?.layout;ia=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||jt}else ia=null;if(l&&!Ae&&!Se&&!ft&&!pe&&R?.border===void 0&&(ge.style.border="none",en(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),l&&!Ae&&pe&&R?.border===void 0&&(en(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),We.style.display="flex",We.style.flexDirection="column",We.style.flex="1 1 0%",We.style.minHeight="0",We.style.maxHeight="100%",We.style.height="100%",x&&(We.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",ft||(ye.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",z.style.flexShrink="0"),x&&(Se||ft||st)&&!l&&(st||(We.style.padding="var(--persona-panel-inset)"),We.style.background="var(--persona-panel-canvas-bg)"),We.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!x&&!l&&(Mn[bt]??Mn["bottom-right"]).split(" ").forEach(Yt=>We.classList.add(Yt)),g){let Rt=o.launcher?.sidebarWidth??"420px";E?We.style.cssText=`
85
85
  position: fixed !important;
86
86
  top: var(--persona-panel-inset) !important;
87
87
  bottom: var(--persona-panel-inset) !important;
88
- width: ${It} !important;
88
+ width: ${Rt} !important;
89
89
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
90
90
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
91
91
  margin: 0 !important;
@@ -94,11 +94,11 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
94
94
  flex-direction: column !important;
95
95
  z-index: ${Vt} !important;
96
96
  ${lt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
97
- `:ke.style.cssText=`
97
+ `:We.style.cssText=`
98
98
  position: fixed !important;
99
99
  top: 0 !important;
100
100
  bottom: 0 !important;
101
- width: ${It} !important;
101
+ width: ${Rt} !important;
102
102
  height: 100vh !important;
103
103
  max-height: 100vh !important;
104
104
  margin: 0 !important;
@@ -118,9 +118,9 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
118
118
  min-height: 0 !important;
119
119
  margin: 0 !important;
120
120
  padding: 0 !important;
121
- box-shadow: ${Ke} !important;
122
- border-radius: ${tt} !important;
123
- ${gt?"border: none !important;":ue?`border: ${Tt} !important;`:""}
121
+ box-shadow: ${Ve} !important;
122
+ border-radius: ${rt} !important;
123
+ ${ft?"border: none !important;":pe?`border: ${Tt} !important;`:""}
124
124
  `,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),ge.style.cssText=`
125
125
  display: flex !important;
126
126
  flex-direction: column !important;
@@ -130,32 +130,32 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
130
130
  min-height: 0 !important;
131
131
  max-height: 100% !important;
132
132
  overflow: hidden !important;
133
- border-radius: ${Rt} !important;
134
- border: ${et} !important;
135
- ${gt&&!at?`box-shadow: ${Et} !important;`:""}
136
- ${at?"background: transparent !important;":""}
137
- `,q.style.cssText=`
133
+ border-radius: ${Pt} !important;
134
+ border: ${ot} !important;
135
+ ${ft&&!st?`box-shadow: ${Et} !important;`:""}
136
+ ${st?"background: transparent !important;":""}
137
+ `,z.style.cssText=`
138
138
  flex-shrink: 0 !important;
139
139
  border-top: none !important;
140
140
  padding: 8px 16px 12px 16px !important;
141
- ${at?"background: transparent !important;":""}
142
- `}if(!v&&!l){let It="max-height: -moz-available !important; max-height: stretch !important;",Zt=g?"":"padding-top: 1.25em !important;",Ea=g?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;ke.style.cssText+=It+Zt+Ea}zo()};fa(),nr(e,o),Xs(e,o),Qs(e,o),Zr=()=>{fa(),nr(e,o),Xs(e,o),Qs(e,o),aa?e.style.setProperty("--persona-artifact-welded-outer-radius",aa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ge=[];Ge.push(()=>{document.removeEventListener("keydown",gd)}),Ge.push(()=>{Xr!==null&&clearTimeout(Xr)});let kn=null,Ln=null;Ge.push(()=>{kn?.(),kn=null,Ln?.(),Ln=null}),Yr&&Ge.push(()=>{Yr?.disconnect(),Yr=null}),Ge.push(()=>{ns?.(),ns=null,al(),At&&(At.remove(),At=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),Z&&Ge.push(()=>{Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),Fe?.destroy(),Fe=null,Ne?.destroy(),Ne=null,fe=null});let Do=null,yd=()=>{Do&&(Do(),Do=null),o.colorScheme==="auto"&&(Do=Dr(()=>{nr(e,o)}))};yd(),Ge.push(()=>{Do&&(Do(),Do=null)}),Ge.push(a);let ga=o.features?.streamAnimation;if(ga?.type&&ga.type!=="none"){let l=_r(ga.type,ga.plugins);l&&(Ai(l,e),Ge.push(()=>ff(e)))}let ma=Hf(wt),Oo=null,j,il=l=>{if(!j)return;let g=l??j.getMessages(),b=o.features?.suggestReplies?.enabled!==!1?Fa(g):null;b?ma.render(b,j,F,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(v=>v.role==="user")?ma.render([],j,F,g):ma.render(o.suggestionChips,j,F,g,o.suggestionChipsConfig)},vn=!1,No=ef(),gr=new Map,Fo=new Map,no=new Map,ll=0,Gg=jn()!==null,on=yi(),pn=0,oo=null,un=!1,ha=!1,ro=0,xn=null,_o=null,cl=!1,ya=!1,dl=null,os=!0,pl=!1,ul=null,Jg=4,ba=24,Xg=80,fl=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},bd=o.voiceRecognition?.autoResume??!1,Nn=l=>{i.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},Cn=()=>{C(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},Qg=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=Dc(c.voiceState),g=!!l.active,b=Number(l.timestamp??0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-b<uv&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?j.toggleVoice().then(()=>{Qe.active=j.isVoiceActive(),Nn("restore"),j.isVoiceActive()&&vr()}):Ca("restore"))},1e3)},Yg=()=>j?Xf(j.getMessages()).filter(l=>!l.__skipPersist):[],va=null,vd=(l,g)=>{typeof console<"u"&&console.error(l,g)},gl=(l,g)=>{let b=()=>{try{let Q=l();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(_=>{vd(g,_)})}catch(Q){return vd(g,Q),null}},v=va,T=v?v.then(()=>b()??void 0):b();if(!T)return;let R=T.finally(()=>{va===R&&(va=null)});va=R};function ml(l){if(!d?.save)return;let b={messages:l?Xf(l):j?Yg():[],metadata:c,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};gl(()=>d.save(b),"[AgentWidget] Failed to persist state:")}let mr=null,xd=()=>ke.querySelector("#persona-scroll-container")||ce,rs=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),un=!1},Cd=()=>{oo!==null&&(cancelAnimationFrame(oo),oo=null),ha=!1,rs()},Zg=()=>vn&&yl()&&(Yt()!=="anchor-top"||td()),hl=()=>{let l=Io()||"Jump to latest",g=Zg();Ht.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),ro>0?(Wo.textContent=String(ro),Wo.style.display="",Ht.setAttribute("aria-label",`${l} (${ro} new)`)):(Wo.textContent="",Wo.style.display="none",Ht.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},wd=()=>{ro!==0&&(ro=0,hl())},yl=()=>Yn()?!on.isFollowing():!Mo(ce,ba),rn=()=>{if(!ra()||Ae){Ht.parentNode&&Ht.remove(),Ht.style.display="none";return}Ht.parentNode!==ge&&ge.appendChild(Ht),dr();let g=Hn(ce)>0&&yl();g?hl():wd(),Ht.style.display=g?"":"none"},ss=()=>{on.pause()&&(Cd(),rn())},so=()=>{on.resume(),wd(),rn()},ao=(l=!1)=>{Yn()&&on.isFollowing()&&(!l&&!vn||(oo!==null&&(cancelAnimationFrame(oo),oo=null),ha=!0,oo=requestAnimationFrame(()=>{oo=null,ha=!1,on.isFollowing()&&em(xd(),l?220:140)})))},Ad=(l,g,b,v=()=>!0)=>{let T=l.scrollTop,R=g(),Q=R-T;if(rs(),Math.abs(Q)<1){un=!0,l.scrollTop=R,pn=l.scrollTop,un=!1;return}let _=performance.now();un=!0;let G=pe=>1-Math.pow(1-pe,3),re=pe=>{if(!v()){rs();return}let se=g();se!==R&&(R=se,Q=R-T);let we=pe-_,Je=Math.min(we/b,1),vt=G(Je),lt=T+Q*vt;l.scrollTop=lt,pn=l.scrollTop,Je<1?mr=requestAnimationFrame(re):(l.scrollTop=R,pn=l.scrollTop,mr=null,un=!1)};mr=requestAnimationFrame(re)},em=(l,g=500)=>{let b=Hn(l)-l.scrollTop;if(Math.abs(b)<1){pn=l.scrollTop;return}if(Math.abs(b)>=Xg){rs(),un=!0,l.scrollTop=Hn(l),pn=l.scrollTop,un=!1;return}Ad(l,()=>Hn(l),g,()=>on.isFollowing())},Sd=()=>{let l=xd();un=!0,l.scrollTop=Hn(l),pn=l.scrollTop,un=!1,rn()},Td=l=>{let g=0,b=l;for(;b&&b!==ce;)g+=b.offsetTop,b=b.offsetParent;return g},Ed=()=>{if($g()!=="last-user-turn")return!1;let l=j?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(R=>R.role==="user");if(!g)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ce.querySelector(`[data-message-id="${b}"]`);if(!v)return!1;let T=Math.min(Math.max(0,Td(v)-Zc()),Hn(ce));return un=!0,ce.scrollTop=T,pn=ce.scrollTop,un=!1,Yt()==="follow"&&!Mo(ce,ba)&&on.pause(),rn(),!0},Md=l=>{Zn.style.height=`${Math.max(0,Math.round(l))}px`,xn&&(xn.spacerHeight=Math.max(0,l))},as=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),rs(),xn=null,Zn.style.height="0px"},tm=l=>{_o!==null&&cancelAnimationFrame(_o),_o=requestAnimationFrame(()=>{_o=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ce.querySelector(`[data-message-id="${g}"]`);if(!b)return;let v=Td(b),T=xn?.spacerHeight??0,R=ce.scrollHeight-T,{targetScrollTop:Q,spacerHeight:_}=sf({anchorOffsetTop:v,topOffset:Zc(),viewportHeight:ce.clientHeight,contentHeight:R});xn={initialSpacerHeight:_,contentHeightAtAnchor:R,spacerHeight:_},Md(_),Ad(ce,()=>Q,220)})},nm=()=>{if(Yn()){if(!on.isFollowing()||Mo(ce,1))return;ao(!vn);return}if(xn&&xn.initialSpacerHeight>0){let l=ce.scrollHeight-xn.spacerHeight,g=af({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:l});g!==xn.spacerHeight&&Md(g)}rn()},om=l=>{let g=Yt();g==="follow"?(so(),ao(!0)):g==="anchor-top"&&(os=!1,pl=!0,tm(l))},rm=()=>{if(Yt()==="anchor-top"){if(pl){os=!1;return}os=!0,as(),so(),ao(!0)}},sm=l=>{let g=new Map;l.forEach(b=>{let v=fl.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!v&&b.role==="assistant"&&(i.emit("assistant:message",b),!ya&&(Yt()!=="anchor-top"||td())&&yl()&&(ro+=1,hl(),rn(),od(ro===1?"1 new message below.":`${ro} new messages below.`))),b.role==="assistant"&&v?.streaming&&b.streaming===!1&&i.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(v?b.approval.status!=="pending"&&i.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):i.emit("approval:requested",{approval:b.approval,message:b}))}),fl.clear(),g.forEach((b,v)=>{fl.set(v,b)})},am=(l,g,b)=>{let v=document.createElement("div"),R=(()=>{let H=s.find(je=>je.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(H,je)=>je==null?!1:typeof je=="string"?(H.textContent=je,!0):(H.appendChild(je),!0),_=new Set,G=new Set,re=s.some(H=>H.renderAskUserQuestion),pe=[],se=[],we=o.enableComponentStreaming!==!1,Je=o.approval!==!1,vt=[];if(g.forEach(H=>{_.add(H.id);let je=re&&zn(H),Se=Je&&H.variant==="approval"&&!!H.approval,Ue=!je&&H.role==="assistant"&&!H.variant&&we&&ta(H);!Se&&no.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(H.id)),!Ue&&Fo.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),Fo.delete(H.id));let kt=zn(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=Zu(H,ll)+kt,Tt=je||Se||Ue?null:tf(No,H.id,ft);if(Tt){v.appendChild(Tt.cloneNode(!0)),zn(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(G.add(H.toolCall.id),Lr(H,o,We.composerOverlay));return}let xt=null,jt=s.find(ue=>!!(H.variant==="reasoning"&&ue.renderReasoning||H.variant==="tool"&&ue.renderToolCall||!H.variant&&ue.renderMessage)),Uo=o.layout?.messages;if(zn(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){gr.delete(H.id),l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ms(H)&&o.features?.suggestReplies?.enabled!==!1)return;if(zn(H)&&o.features?.askUserQuestion?.enabled!==!1){let ue=s.find(Et=>typeof Et.renderAskUserQuestion=="function");if(ue&&ht.current){let Et=gr.get(H.id),Kt=Et!==ft,Nt=null;if(Kt){let{payload:et,complete:Rt}=qn(H),De=H.id,tt=()=>ht.current?.getMessages().find(sn=>sn.id===De);Nt=ue.renderAskUserQuestion({message:H,payload:et,complete:Rt,resolve:sn=>{let zo=tt();zo&&ht.current?.resolveAskUserQuestion(zo,sn)},dismiss:()=>{let sn=tt();sn?.agentMetadata?.awaitingLocalTool&&(ht.current?.markAskUserQuestionResolved(sn),ht.current?.resolveAskUserQuestion(sn,"(dismissed)"))},config:o})}let at=Et!=null;if(Kt&&Nt===null&&!at){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(G.add(H.toolCall.id),Lr(H,o,We.composerOverlay));return}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${H.id}`,Ke.setAttribute("data-wrapper-id",H.id),Ke.setAttribute("data-ask-plugin-stub","true"),Ke.setAttribute("data-preserve-runtime","true"),v.appendChild(Ke),pe.push({messageId:H.id,fingerprint:ft,bubble:Nt});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(G.add(H.toolCall.id),Lr(H,o,We.composerOverlay));return}}else if(Se){let ue=s.find(at=>typeof at.renderApproval=="function")??r,Kt=no.get(H.id)!==ft,Nt=null;if(Kt&&ue?.renderApproval){let at=H.id,Ke=(et,Rt)=>{let De=ht.current?.getMessages().find(tt=>tt.id===at);De?.approval&&(De.approval.toolType==="webmcp"?ht.current?.resolveWebMcpApproval(De.id,et):ht.current?.resolveApproval(De.approval,et,Rt))};Nt=ue.renderApproval({message:H,defaultRenderer:()=>Hi(H,o),config:o,approve:et=>Ke("approved",et),deny:et=>Ke("denied",et)})}if(Kt&&Nt===null)l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(H.id),xt=Hi(H,o);else{let at=document.createElement("div");at.className="persona-flex",at.id=`wrapper-${H.id}`,at.setAttribute("data-wrapper-id",H.id),at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),v.appendChild(at),vt.push({messageId:H.id,fingerprint:ft,bubble:Nt});return}}else if(jt)if(H.variant==="reasoning"&&H.reasoning&&jt.renderReasoning){if(!ae)return;xt=jt.renderReasoning({message:H,defaultRenderer:()=>Sc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&jt.renderToolCall){if(!ve)return;xt=jt.renderToolCall({message:H,defaultRenderer:()=>Ec(H,o),config:o})}else jt.renderMessage&&(xt=jt.renderMessage({message:H,defaultRenderer:()=>{let ue=Ur(H,b,Uo,o.messageActions,le,{loadingIndicatorRenderer:R,widgetConfig:o});return H.role!=="user"&&Wc(ue,H,o,j),ue},config:o}));if(!xt&&Ue){let ue=_i(H);if(ue){let Et=Fo.get(H.id),Kt=Et!==ft,Nt=o.wrapComponentDirectiveInBubble!==!1&&En.getOptions(ue.component)?.bubbleChrome!==!1,at=null;if(Kt){let Ke=Fi(ue,{config:o,message:H,transform:b});if(Ke&&ue.component==="PersonaArtifactInline"){let et=Ke.hasAttribute("data-artifact-inline")?Ke:Ke.querySelector("[data-artifact-inline]"),Rt=et?.getAttribute("data-artifact-inline")??"",De=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Rt):Rt,tt=Rt?l.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${De}"]`)??null:null;et&&tt&&tt!==et&&Ku(tt)&&(et===Ke?Ke=tt:et.replaceWith(tt))}if(Ke)if(Nt){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${H.id}`,et.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Rt=document.createElement("div");Rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),et.appendChild(Rt)}et.appendChild(Ke),at=et}else{let et=document.createElement("div");if(et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",et.id=`bubble-${H.id}`,et.setAttribute("data-message-id",H.id),et.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Rt=document.createElement("div");Rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),et.appendChild(Rt)}et.appendChild(Ke),at=et}}if(at||Et!=null){let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${H.id}`,Ke.setAttribute("data-wrapper-id",H.id),Ke.setAttribute("data-component-directive-stub","true"),Ke.setAttribute("data-preserve-runtime","true"),Nt||Ke.classList.add("persona-w-full"),v.appendChild(Ke),se.push({messageId:H.id,fingerprint:ft,bubble:at});return}}}if(!xt)if(H.variant==="reasoning"&&H.reasoning){if(!ae)return;xt=Sc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!ve)return;xt=Ec(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;xt=Hi(H,o)}else{let ue=o.layout?.messages;ue?.renderUserMessage&&H.role==="user"?xt=ue.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):ue?.renderAssistantMessage&&H.role==="assistant"?xt=ue.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):xt=Ur(H,b,ue,o.messageActions,le,{loadingIndicatorRenderer:R,widgetConfig:o}),H.role!=="user"&&xt&&Wc(xt,H,o,j)}let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${H.id}`,gt.setAttribute("data-wrapper-id",H.id),H.role==="user"&&gt.classList.add("persona-justify-end"),xt?.getAttribute("data-persona-component-directive")==="true"&&gt.classList.add("persona-w-full"),gt.appendChild(xt),nf(No,H.id,ft,gt),v.appendChild(gt)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(je=>{let Se=je.getAttribute("data-persona-ask-sheet-for");Se&&!G.has(Se)&&go(We.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let H=[],je=[];g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&ve){je.push(Se);return}Se.variant==="reasoning"&&!ae||(je.length>1&&H.push(je),je=[])}),je.length>1&&H.push(je),H.forEach((Se,Ue)=>{let kt=Se.map(Et=>Array.from(v.children).find(Kt=>Kt instanceof HTMLElement&&Kt.getAttribute("data-wrapper-id")===Et.id)).filter(Et=>!!Et);if(kt.length<2)return;let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-tool-group-${Ue}-${Se[0].id}`,ft.setAttribute("data-wrapper-id",`tool-group-${Ue}-${Se[0].id}`);let Tt=document.createElement("div");Tt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Tt.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${Se.length} tools`,Uo=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Et=>Et.toolCall).filter(Et=>!!Et),defaultSummary:jt,config:o});Q(xt,Uo)||(xt.textContent=jt);let gt=document.createElement("div");gt.className="persona-tool-group-stack persona-flex persona-flex-col";let ue=o.features?.toolCallDisplay?.groupedMode==="summary";Tt.appendChild(xt),ue||Tt.appendChild(gt),ft.appendChild(Tt),kt[0].before(ft),kt.forEach((Et,Kt)=>{if(ue){Et.remove();return}let Nt=document.createElement("div");Nt.className="persona-tool-group-item persona-relative",Nt.setAttribute("data-persona-tool-group-item","true"),Kt<kt.length-1&&Nt.setAttribute("data-persona-tool-group-connector","true"),Nt.appendChild(Et),gt.appendChild(Nt)})})}of(No,_);let lt=g.some(H=>H.role==="assistant"&&H.streaming),Vt=g[g.length-1],Ot=Vt?.role==="assistant"&&!Vt.streaming&&Vt.variant!=="approval";if(vn&&g.some(H=>H.role==="user")&&!lt&&!Ot){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:sr},je=s.find(Ue=>Ue.renderLoadingIndicator),Se=null;if(je?.renderLoadingIndicator&&(Se=je.renderLoadingIndicator(H)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(H)),Se===null&&(Se=sr()),Se){let Ue=document.createElement("div"),kt=o.loadingIndicator?.showBubble!==!1;Ue.className=kt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ue.setAttribute("data-typing-indicator","true"),Ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ue.appendChild(Se);let ft=document.createElement("div");ft.className="persona-flex",ft.id="wrapper-typing-indicator",ft.setAttribute("data-wrapper-id","typing-indicator"),ft.appendChild(Ue),v.appendChild(ft)}}if(!vn&&g.length>0){let H=g[g.length-1],je={config:o,lastMessage:H,messageCount:g.length},Se=s.find(kt=>kt.renderIdleIndicator),Ue=null;if(Se?.renderIdleIndicator&&(Ue=Se.renderIdleIndicator(je)),Ue===null&&o.loadingIndicator?.renderIdle&&(Ue=o.loadingIndicator.renderIdle(je)),Ue){let kt=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;kt.className=ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),kt.setAttribute("data-idle-indicator","true"),kt.appendChild(Ue);let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id="wrapper-idle-indicator",Tt.setAttribute("data-wrapper-id","idle-indicator"),Tt.appendChild(kt),v.appendChild(Tt)}}if(hi(l,v),pe.length>0)for(let{messageId:H,fingerprint:je,bubble:Se}of pe){let Ue=l.querySelector(`#wrapper-${H}`);Ue&&Se!==null&&(Ue.replaceChildren(Se),Ue.setAttribute("data-bubble-fp",je),gr.set(H,je))}if(gr.size>0)for(let H of gr.keys())_.has(H)||gr.delete(H);if(se.length>0)for(let{messageId:H,fingerprint:je,bubble:Se}of se){let Ue=l.querySelector(`#wrapper-${H}`);Ue&&Se!==null&&(Ue.replaceChildren(Se),Ue.setAttribute("data-bubble-fp",je),Fo.set(H,je))}if(Fo.size>0)for(let H of Fo.keys())_.has(H)||Fo.delete(H);if(vt.length>0)for(let{messageId:H,fingerprint:je,bubble:Se}of vt){let Ue=l.querySelector(`#wrapper-${H}`);Ue&&Se!==null&&(Ue.replaceChildren(Se),Ue.setAttribute("data-bubble-fp",je),no.set(H,je))}if(no.size>0)for(let H of no.keys())_.has(H)||no.delete(H)},is=(l,g,b)=>{am(l,g,b),pd()},ls=null,im=()=>{if(ls)return;let l=b=>{let v=b.composedPath();v.includes(ke)||ct&&v.includes(ct)||yt(!1,"user")};ls=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},kd=()=>{if(!ls)return;(e.ownerDocument??document).removeEventListener("pointerdown",ls,!0),ls=null};Ge.push(()=>kd());let cs=null,lm=()=>{if(cs)return;let l=b=>{b.key==="Escape"&&(b.isComposing||yt(!1,"user"))};cs=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Ld=()=>{if(!cs)return;(e.ownerDocument??document).removeEventListener("keydown",cs,!0),cs=null};Ge.push(()=>Ld());let ds=!1,Pd=new Set,cm=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},hr=()=>{if(!Y())return;let l=We.peekBanner,g=We.peekTextNode;if(!l||!g)return;if(U){l.classList.remove("persona-pill-peek--visible");return}let b=j?.getMessages()??[],v;for(let Ot=b.length-1;Ot>=0;Ot--){let H=b[Ot];if(H.role==="assistant"&&H.content){v=H;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let T=v.content,R=!!v.streaming,Q=cm(),_=xi(Q),G=_.type!=="none"?_r(_.type,Q?.plugins):null,re=G?.isAnimating?.(v)===!0,pe=G!==null&&(R||re);pe&&G&&!Pd.has(G.name)&&(Ai(G,e),Pd.add(G.name));let se=pe&&G?.containerClass?G.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==se&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),se&&we!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),pe?(g.style.setProperty("--persona-stream-step",`${_.speed}ms`),g.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Je=pe?Ci(T,_.buffer,G,v,R):T;if(pe&&_.placeholder==="skeleton"&&R&&(!Je||!Je.trim())){let Ot=document.createElement("div"),H=zs();H.classList.add("persona-pill-peek__skeleton"),Ot.appendChild(H),hi(g,Ot)}else{let Ot=Math.max(0,Je.length-100),H=Je.length>100?Je.slice(-100):Je,je=Rn(H);if(!pe||!G){let Se=Je.length>100?`\u2026${H}`:H;g.textContent!==Se&&(g.textContent=Se)}else{let Se=je;(G.wrap==="char"||G.wrap==="word")&&(Se=Us(je,G.wrap,`peek-${v.id}`,{skipTags:G.skipTags,startIndex:Ot}));let Ue=document.createElement("div");if(Ue.innerHTML=Se,G.useCaret&&H.length>0){let kt=wi(),ft=Ue.querySelectorAll(".persona-stream-char, .persona-stream-word"),Tt=ft[ft.length-1];Tt?.parentNode?Tt.parentNode.insertBefore(kt,Tt.nextSibling):Ue.appendChild(kt)}hi(g,Ue),G.onAfterRender?.({container:g,bubble:l,messageId:v.id,message:v,speed:_.speed,duration:_.duration})}}let Vt=vn||ds;l.classList.toggle("persona-pill-peek--visible",Vt)};if(Y()){let l=We.peekBanner;if(l){let v=T=>{T.preventDefault(),T.stopPropagation(),yt(!0,"user")};l.addEventListener("pointerdown",v),Ge.push(()=>{l.removeEventListener("pointerdown",v)})}let g=()=>{ds||(ds=!0,hr())},b=()=>{ds&&(ds=!1,hr())};ye.addEventListener("pointerenter",g),ye.addEventListener("pointerleave",b),Ge.push(()=>{ye.removeEventListener("pointerenter",g),ye.removeEventListener("pointerleave",b)}),ct&&(ct.addEventListener("pointerenter",g),ct.addEventListener("pointerleave",b),Ge.push(()=>{ct.removeEventListener("pointerenter",g),ct.removeEventListener("pointerleave",b)}))}let dm=l=>{let g=o.launcher?.composerBar??{},b=g.expandedSize??"anchored",v=g.bottomOffset??"16px",T=g.collapsedMaxWidth,R=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",_=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",se=ke.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",ct){let we=ct.style;we.bottom=v,we.width=T??""}if(l&&b!=="fullscreen"){if(b==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=_,se.maxWidth=re,se.maxHeight=G,se.height=G;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${v} + ${pe})`,se.top=Q,se.width=R,se.maxWidth=re}},ps=()=>{if(!O())return;if(Y()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=U?"expanded":"collapsed";ke.dataset.state=pe,ke.dataset.expandedSize=re,ct&&(ct.dataset.state=pe,ct.dataset.expandedSize=re),ke.style.removeProperty("display"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),dm(U),ge.style.display=U?"flex":"none",fa(),U?(im(),lm()):(kd(),Ld()),hr();return}let l=Wt(o),g=e.ownerDocument.defaultView??window,b=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,T=g.innerWidth<=b,R=v&&T&&A,Q=tn(o).reveal;U?(ke.style.removeProperty("display"),ke.style.display=l?"flex":"",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),$t?$t.element.style.display="none":qt&&(qt.style.display="none")):(l?l&&(Q==="overlay"||Q==="push")&&!R?(ke.style.removeProperty("display"),ke.style.display="flex",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.setProperty("display","none","important"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.display="",ke.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),$t?$t.element.style.display=l?"none":"":qt&&(qt.style.display=l?"none":""))},yt=(l,g="user")=>{if(!O()||U===l)return;let b=U;U=l,ps();let v=(()=>{let R=o.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,_=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=Q.innerWidth<=G,pe=Wt(o)&&_&&re,se=Y()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||_&&re&&A||pe||se})();if(U&&v){if(!kn){let R=e.getRootNode(),Q=R instanceof ShadowRoot?R.host:e.closest(".persona-host");Q&&(kn=fc(Q,o.launcher?.zIndex??zt))}Ln||(Ln=gc(e.ownerDocument))}else U||(kn?.(),kn=null,Ln?.(),Ln=null);U&&(gs(),Ed()||(Yt()==="follow"?ao(!0):Sd()));let T={open:U,source:g,timestamp:Date.now()};U&&!b?i.emit("widget:opened",T):!U&&b&&i.emit("widget:closed",T),i.emit("widget:state",{open:U,launcherEnabled:A,voiceActive:Qe.active,streaming:j.isStreaming()})},bl=l=>{dt(l?"stop":"send"),K&&(K.disabled=l),ma.buttons.forEach(g=>{g.disabled=l}),q.dataset.personaComposerStreaming=l?"true":"false",q.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},vl=()=>{Qe.active||F&&F.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>vl(),200)});let Rd=()=>{X.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",x.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",F.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=ce.querySelector("[data-persona-intro-card]");if(l){let b=o.copy?.showWelcomeCard!==!1;l.style.display=b?"":"none",b?(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)&&!j?.isStreaming()&&(ne.textContent=o.copy?.sendButtonLabel??"Send"),F.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',F.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(g=>({...g,sessionId:l}))}});let $o=null,pm=()=>{$o==null&&($o=setInterval(()=>{let l=xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval($o),$o=null;return}let g=Date.now();l.forEach(b=>{let v=Number(b.getAttribute("data-tool-elapsed"));v&&(b.textContent=$a(g-v))})},100))},xl=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((Q,_)=>xl(Q,g[_]));let b=l,v=g,T=Object.keys(b),R=Object.keys(v);return T.length===R.length&&T.every(Q=>Object.prototype.hasOwnProperty.call(v,Q)&&xl(b[Q],v[Q]))},Id=l=>{let{content:g,rawContent:b,llmContent:v,...T}=l;return T},Cl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!ta(l),um=(l,g,b)=>{if(l.length!==g.length)return!1;let v=l[b.index],T=g[b.index];return!v||!T||v.id!==b.id||T.id!==b.id?!1:(!Object.is(v.content,T.content)||!Object.is(v.rawContent,T.rawContent)||!Object.is(v.llmContent,T.llmContent))&&Cl(v)&&Cl(T)&&xl(Id(v),Id(T))},Wd=null,yr=null,jo=null,Fn=null,xa=l=>{Wd=l;let g,b;yr=null;for(let T=l.length-1;T>=0;T-=1){let R=l[T];if(!g&&R.role==="user"&&(g=R),!b&&R.role==="assistant"&&(b=R),!yr&&Cl(R)&&(yr={index:T,id:R.id}),g&&b&&yr)break}is(xe,l,Oe),ic(xe,yn.artifacts,{suppressTransition:vn}),pm(),il(l),ao(!vn),sm(l),l.length===0&&(as(),os=!0,pl=!1),!cl||ya?(cl=!0,dl=g?.id??null,ul=b?.id??null):g&&g.id!==dl?(dl=g.id,om(g.id)):b&&b.id!==ul&&rm(),b&&(ul=b.id);let v=Qe.lastUserMessageId;g&&g.id!==v&&(Qe.lastUserMessageId=g.id,i.emit("user:message",g)),Qe.lastUserMessageWasVoice=!!g?.viaVoice,ml(l),hr()},wl=()=>{Fn!==null&&(cancelAnimationFrame(Fn),Fn=null);let l=jo;jo=null,l&&xa(l)},Hd=()=>{Fn!==null&&cancelAnimationFrame(Fn),Fn=null,jo=null},fm=l=>{let g=jo??Wd;if(vn&&g&&yr&&um(g,l,yr)){jo=l,Fn===null&&(Fn=requestAnimationFrame(()=>{Fn=null;let b=jo;jo=null,b&&xa(b)}));return}if(l.length===0){Hd(),xa(l);return}wl(),xa(l)};j=new Hr(o,{onMessagesChanged(l){fm(l)},onStatusChanged(l){let g=o.statusIndicator??{};bt(k,(v=>v==="idle"?g.idleText??Dt.idle:v==="connecting"?g.connectingText??Dt.connecting:v==="connected"?g.connectedText??Dt.connected:v==="error"?g.errorText??Dt.error:v==="paused"?g.pausedText??Dt.paused:v==="resuming"?g.resumingText??Dt.resuming:Dt[v])(l),g,l)},onStreamingChanged(l){l||(j?.getMessages().length===0?Hd():wl()),vn=l,bl(l),j&&is(xe,j.getMessages(),Oe),l||ao(!0),rn(),od(l?"Responding\u2026":"Response complete."),hr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":_n(),vr();break;case"processing":_n(),Sm();break;case"speaking":_n(),Tm();break;default:l==="idle"&&j.isBargeInActive()?(_n(),vr(),K?.setAttribute("aria-label","End voice session")):(Qe.active=!1,_n(),Nn("system"),Cn());break}},onArtifactsState(l){yn=l,l.artifacts.length===0&&(pr=!1),ic(xe,l.artifacts,{suppressTransition:vn}),On(),ml()},onReconnect(l){let{executionId:g,lastEventId:b}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:g,after:b}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:g,after:b,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:g,after:b})}}),ht.current=j,Ge.push(()=>j.cancel());let Al=null;if(j.onReadAloudChange((l,g)=>{cd=l,dd=g,pd();let b=l??Al;l&&(Al=l);let v=b?j.getMessages().find(T=>T.id===b)??null:null;i.emit("message:read-aloud",{messageId:b,message:v,state:g,timestamp:Date.now()}),g==="idle"&&(Al=null)}),cl=!0,o.voiceRecognition?.provider?.type==="runtype")try{j.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&j.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Ne||o.onSSEEvent)&&j.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),ze?.processEvent(l,g),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let Bd=()=>{o.resume&&typeof o.reconnectStream=="function"&&j.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=Dc(l.metadata),I.syncFromMetadata()),l.messages?.length){ya=!0;try{j.hydrateMessages(l.messages)}finally{ya=!1}}l.artifacts?.length&&j.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Bd()):Bd();let Dd=()=>{!Y()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||yt(!0,"auto")},gm=(l,g)=>l?g?{refs:[...l.refs,...g.refs],finalize:async()=>{let[b,v]=await Promise.allSettled([l.finalize(),g.finalize()]),T=[];return b.status==="fulfilled"?T.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),v.status==="fulfilled"?T.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),vv(T)}}:l:g,mm=()=>{let g=F.getInlineMessageFields?.();return g&&g.contentSegments.some(v=>v.kind==="mention")?g.contentSegments:void 0},us=!1,hm=async l=>{let g=F.value.trim(),b=Lt?.hasAttachments()??!1,v=g?await(nn?.takeInlineCommand(g)??Promise.resolve(null)):null;if(v?.kind==="action"){F.value="",F.style.height="auto",fs(),nn?.clear();return}let T=nn?.collectForSubmit()??null,R=v?.kind==="server"?v.mentions:null,Q=gm(T,R),_=v?.kind==="prompt"?v.sendText:g,G=!!T&&T.refs.length>0;if(!_&&!b&&!G&&!R)return;Dd();let re;b&&(re=[],re.push(...Lt.getContentParts()),_&&re.push(bo(_)));let pe=v?.kind==="prompt"?void 0:mm();F.value="",F.style.height="auto",fs(),j.sendMessage(_,{contentParts:re,mentions:Q??void 0,contentSegments:pe,viaVoice:l?.viaVoice}),b&&Lt.clearAttachments(),T&&nn?.clear()},Sl=async l=>{if(!us){us=!0;try{await hm(l)}finally{us=!1}}},Od=l=>{if(l.preventDefault(),j.isStreaming()){j.cancel(),ze?.reset(),Fe?.update();return}us||Sl()},ym=()=>o.features?.composerHistory!==!1,Tl={...dc},El=!1,fs=()=>{Tl={...dc}},bm=()=>j.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),vm=l=>{if(!F)return;El=!0,F.value=l,F.dispatchEvent(new Event("input",{bubbles:!0})),El=!1;let g=F.value.length;F.setSelectionRange(g,g)},xm=l=>{El||(l.isComposing||nn?.handleInput(l.inputType??void 0),fs())},Cm=l=>{if(F&&!(!l.isComposing&&nn?.handleKeydown(l))){if(ym()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=F.selectionStart===0&&F.selectionEnd===0,b=Yu({direction:l.key==="ArrowUp"?"up":"down",history:bm(),currentValue:F.value,atStart:g,state:Tl});if(Tl=b.state,b.handled){l.preventDefault(),b.value!==void 0&&vm(b.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(j.isStreaming()){l.preventDefault();return}if(us){l.preventDefault();return}fs(),l.preventDefault(),ne.click()}}},Nd=l=>{l.key!=="Escape"||l.isComposing||j.isStreaming()&&l.composedPath().includes(ge)&&(j.cancel(),ze?.reset(),Fe?.update(),fs(),l.preventDefault(),l.stopImmediatePropagation())},wm=async l=>{if(o.attachments?.enabled!==!0||!Lt)return;let g=mv(l.clipboardData);g.length!==0&&(l.preventDefault(),await Lt.handleFiles(g))},fn=null,Pn=!1,br=null,St=null,Fd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ca=(l="user")=>{if(Pn||j.isStreaming())return;let g=Fd();if(!g)return;fn=new g;let v=(o.voiceRecognition??{}).pauseDuration??2e3;fn.continuous=!0,fn.interimResults=!0,fn.lang="en-US";let T=F.value;fn.onresult=R=>{let Q="",_="";for(let re=0;re<R.results.length;re++){let pe=R.results[re],se=pe[0].transcript;pe.isFinal?Q+=se+" ":_=se}let G=T+Q+_;F.value=G,br&&clearTimeout(br),(Q||_)&&(br=window.setTimeout(()=>{F.value.trim()&&fn&&Pn&&(io(),Sl({viaVoice:!0}))},v))},fn.onerror=R=>{R.error!=="no-speech"&&io()},fn.onend=()=>{if(Pn){let R=F.value.trim();R&&R!==T.trim()&&Sl({viaVoice:!0}),io()}};try{if(fn.start(),Pn=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Nn(l),Cn(),K){let R=o.voiceRecognition??{};St={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:R.iconName??"mic",iconSize:parseFloat(R.iconSize??o.sendButton?.size??"40")||24};let Q=R.recordingBackgroundColor,_=R.recordingIconColor,G=R.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=_??"var(--persona-voice-recording-indicator, #ffffff)",_){let re=K.querySelector("svg");re&&re.setAttribute("stroke",_)}G&&(K.style.borderColor=G),K.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(l="user")=>{if(Pn){if(Pn=!1,br&&(clearTimeout(br),br=null),fn){try{fn.stop()}catch{}fn=null}if(Qe.active=!1,Nn(l),Cn(),K){if(K.classList.remove("persona-voice-recording"),St){K.style.backgroundColor=St.backgroundColor,K.style.color=St.color,K.style.borderColor=St.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",St.color||"currentColor"),St=null}K.setAttribute("aria-label","Start voice recognition")}}},Am=(l,g)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=l?.provider?.type==="runtype",T=l?.provider?.type==="custom";if(!(b||v||T))return null;let Q=m("div","persona-send-button-wrapper"),_=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let G=l?.iconName??"mic",re=g?.size??"40px",pe=l?.iconSize??re,se=parseFloat(pe)||24,we=l?.backgroundColor??g?.backgroundColor,Je=l?.iconColor??g?.textColor;_.style.width=pe,_.style.height=pe,_.style.minWidth=pe,_.style.minHeight=pe,_.style.fontSize="18px",_.style.lineHeight="1",Je?_.style.color=Je:_.style.color="var(--persona-text, #111827)";let lt=oe(G,se,Je||"currentColor",1.5);lt?_.appendChild(lt):_.textContent="\u{1F3A4}",we?_.style.backgroundColor=we:_.style.backgroundColor="",l?.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l?.borderColor&&(_.style.borderColor=l.borderColor),l?.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l?.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),Q.appendChild(_);let Vt=l?.tooltipText??"Start voice recognition";if((l?.showTooltip??!1)&&Vt){let H=m("div","persona-send-button-tooltip");H.textContent=Vt,Q.appendChild(H)}return{micButton:_,micButtonWrapper:Q}},Ml=()=>{if(!K||St)return;let l=o.voiceRecognition??{};St={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},kl=(l,g)=>{if(!K)return;let b=K.querySelector("svg");b&&b.remove();let v=St?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),T=oe(l,v,g,1.5);T&&K.appendChild(T)},wa=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},vr=()=>{if(!K)return;Ml();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,b=l.recordingIconColor,v=l.recordingBorderColor;if(wa(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let T=K.querySelector("svg");T&&T.setAttribute("stroke",b)}v&&(K.style.borderColor=v),K.setAttribute("aria-label","Stop voice recognition")},Sm=()=>{if(!K)return;Ml();let l=o.voiceRecognition??{},g=j.getVoiceInterruptionMode(),b=l.processingIconName??"loader",v=l.processingIconColor??St?.color??"",T=l.processingBackgroundColor??St?.backgroundColor??"",R=l.processingBorderColor??St?.borderColor??"";wa(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=T,K.style.borderColor=R;let Q=v||"currentColor";K.style.color=Q,kl(b,Q),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},Tm=()=>{if(!K)return;Ml();let l=o.voiceRecognition??{},g=j.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",v=l.speakingIconName??b,T=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??St?.color??"":St?.color??""),R=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":St?.backgroundColor??""),Q=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":St?.borderColor??"");wa(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=R,K.style.borderColor=Q;let _=T||"currentColor";K.style.color=_,kl(v,_);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",G),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},_n=()=>{K&&(wa(),St&&(K.style.backgroundColor=St.backgroundColor??"",K.style.color=St.color??"",K.style.borderColor=St.borderColor??"",kl(St.iconName,St.color||"currentColor"),St=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Aa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=j.getVoiceStatus(),g=j.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){j.stopVoicePlayback();return}if(j.isBargeInActive()){j.stopVoicePlayback(),j.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,Cn(),Nn("user"),_n()});return}j.toggleVoice().then(()=>{Qe.active=j.isVoiceActive(),Qe.manuallyDeactivated=!j.isVoiceActive(),Cn(),Nn("user"),j.isVoiceActive()?vr():_n()});return}if(Pn){let l=F.value.trim();Qe.manuallyDeactivated=!0,Cn(),io("user"),l&&(F.value="",F.style.height="auto",j.sendMessage(l))}else Qe.manuallyDeactivated=!1,Cn(),Ca("user")};sd=Aa,K&&(K.addEventListener("click",Aa),Ge.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(j.isVoiceActive()&&j.toggleVoice(),_n()):io("system"),K&&K.removeEventListener("click",Aa)}));let Em=i.on("assistant:complete",()=>{bd&&(Qe.active||Qe.manuallyDeactivated||bd==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?j.toggleVoice().then(()=>{Qe.active=j.isVoiceActive(),Nn("auto"),j.isVoiceActive()&&vr()}):Ca("auto"))},600))});Ge.push(Em);let Mm=i.on("action:resubmit",()=>{setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)});Ge.push(Mm);let _d=()=>{yt(!U,"user")},$t=null,qt=null;if(A&&!Y()){let{instance:l,element:g}=vc({config:o,plugins:s,onToggle:_d});$t=l,l||(qt=g)}$t?e.appendChild($t.element):qt&&e.appendChild(qt),ps(),il(),Rd(),bl(j.isStreaming()),Ed()||(Yt()==="follow"?ao(!0):Sd()),Qg(),$&&(!A||Y()?setTimeout(()=>vl(),0):U&&setTimeout(()=>vl(),200));let gs=()=>{if(Y()){dr(),ps();return}let l=Wt(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640,Q=v.innerWidth<=R,_=T&&Q&&A;try{if(_){Zr(),es=ua();return}let G=!1;V&&(V=!1,Zr(),G=!0);let re=ua();if(!G&&re!==es&&(Zr(),G=!0),es=re,G&&sl(),!A&&!l){ye.style.height="",ye.style.width="";return}if(!g&&!l){let se=o?.launcher?.width??o?.launcherWidth??cn;ye.style.width=se,ye.style.maxWidth=se}if(pa(),!b){let pe=v.innerHeight,se=64,we=o.launcher?.heightOffset??0,Je=Math.max(200,pe-se),vt=Math.min(640,Je),lt=Math.max(200,vt-we);ye.style.height=`${lt}px`}}finally{if(dr(),ps(),U&&A){let re=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),pe=o.launcher?.sidebarMode??!1,se=o.launcher?.mobileFullscreen??!0,we=Wt(o)&&se&&re,Je=pe||se&&re&&A||we;if(Je&&!Ln){let vt=e.getRootNode(),lt=vt instanceof ShadowRoot?vt.host:e.closest(".persona-host");lt&&!kn&&(kn=fc(lt,o.launcher?.zIndex??zt)),Ln=gc(e.ownerDocument)}else Je||(kn?.(),kn=null,Ln?.(),Ln=null)}}};gs();let $d=e.ownerDocument.defaultView??window;if($d.addEventListener("resize",gs),Ge.push(()=>$d.removeEventListener("resize",gs)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{dr()});l.observe(q),Ge.push(()=>l.disconnect())}pn=ce.scrollTop;let jd=Hn(ce),km=()=>{let l=ce.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??ce.ownerDocument.getSelection()},Ll=()=>rf(km(),ce),Ud=()=>{let l=ce.scrollTop,g=Hn(ce),b=g<jd;if(jd=g,!Yn()){pn=l,rn();return}let{action:v,nextLastScrollTop:T}=bi({following:on.isFollowing(),currentScrollTop:l,lastScrollTop:pn,nearBottom:Mo(ce,ba),userScrollThreshold:Jg,isAutoScrolling:un||ha||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=T,v==="resume"){Ll()||so();return}v==="pause"&&ss()};if(ce.addEventListener("scroll",Ud,{passive:!0}),Ge.push(()=>ce.removeEventListener("scroll",Ud)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{nm()});l.observe(xe),l.observe(ce),Ge.push(()=>l.disconnect())}let zd=()=>{Yn()&&on.isFollowing()&&Ll()&&ss()},qd=ce.ownerDocument;qd.addEventListener("selectionchange",zd),Ge.push(()=>{qd.removeEventListener("selectionchange",zd)});let Lm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Vd=l=>{ed()&&Yn()&&on.isFollowing()&&Lm.has(l.key)&&ss()},Kd=l=>{if(!ed()||!Yn()||!on.isFollowing())return;let g=l.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&ss()};ce.addEventListener("keydown",Vd),ce.addEventListener("focusin",Kd),Ge.push(()=>{ce.removeEventListener("keydown",Vd),ce.removeEventListener("focusin",Kd)});let Gd=l=>{if(!Yn())return;let g=vi({following:on.isFollowing(),deltaY:l.deltaY,nearBottom:Mo(ce,ba),resumeWhenNearBottom:!0});g==="pause"?ss():g==="resume"&&!Ll()&&so()};ce.addEventListener("wheel",Gd,{passive:!0}),Ge.push(()=>ce.removeEventListener("wheel",Gd)),Ht.addEventListener("click",()=>{as(),ce.scrollTop=ce.scrollHeight,pn=ce.scrollTop,so(),ao(!0),rn()}),Ge.push(()=>Ht.remove()),Ge.push(()=>{Cd(),as()});let Jd=()=>{E&&(Oo&&(E.removeEventListener("click",Oo),Oo=null),O()?(E.style.display="",Oo=()=>{yt(!1,"user")},E.addEventListener("click",Oo)):E.style.display="none")};Jd(),(()=>{let{clearChatButton:l}=We;l&&l.addEventListener("click",()=>{j.clearMessages(),No.clear(),so(),go(We.composerOverlay);try{localStorage.removeItem(Gr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gr}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Gr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&gl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),Ne?.clear(),ze?.reset(),Fe?.update()})})(),Te&&Te.addEventListener("submit",Od);let Xd=[["keydown",Cm],["input",xm],["paste",wm],["focus",zg]],Qd=l=>{if(l)for(let[g,b]of Xd)l.addEventListener(g,b)},Yd=l=>{if(l)for(let[g,b]of Xd)l.removeEventListener(g,b)};Qd(F),nn?.onComposerSwap((l,g)=>{Yd(g),F=l,Qd(l)});let Zd=e.ownerDocument??document;Zd.addEventListener("keydown",Nd,!0);let ep="persona-attachment-drop-active",ms=0,Pl=()=>{ms=0,ge.classList.remove(ep)},xr=()=>o.attachments?.enabled===!0&&Lt!==null,tp=l=>{!Ui(l.dataTransfer)||!xr()||(ms++,ms===1&&ge.classList.add(ep))},np=l=>{!Ui(l.dataTransfer)||!xr()||(ms--,ms<=0&&Pl())},op=l=>{!Ui(l.dataTransfer)||!xr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},rp=l=>{if(!Ui(l.dataTransfer)||!xr())return;l.preventDefault(),l.stopPropagation(),Pl();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&Lt.handleFiles(g)},lo=!0;ge.addEventListener("dragenter",tp,lo),ge.addEventListener("dragleave",np,lo),e.addEventListener("dragover",op,lo),e.addEventListener("drop",rp,lo);let Sa=e.ownerDocument,sp=l=>{xr()&&l.preventDefault()},ap=l=>{xr()&&l.preventDefault()};Sa.addEventListener("dragover",sp),Sa.addEventListener("drop",ap),Ge.push(()=>{Te&&Te.removeEventListener("submit",Od),Yd(F),Zd.removeEventListener("keydown",Nd,!0),nn?.destroy()}),Ge.push(()=>{ge.removeEventListener("dragenter",tp,lo),ge.removeEventListener("dragleave",np,lo),e.removeEventListener("dragover",op,lo),e.removeEventListener("drop",rp,lo),Sa.removeEventListener("dragover",sp),Sa.removeEventListener("drop",ap),Pl()}),Ge.push(()=>{j.cancel()}),$t?Ge.push(()=>{$t?.destroy()}):qt&&Ge.push(()=>{qt?.remove()});let Bt={update(l){let g=o.toolCall,b=o.messageActions,v=o.layout?.messages,T=o.colorScheme,R=o.loadingIndicator,Q=o.iterationDisplay,_=o.features?.showReasoning,G=o.features?.showToolCalls,re=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type;o={...o,...l},fa(),nr(e,o),Xs(e,o),Qs(e,o),On(),o.colorScheme!==T&&yd();let we=Ys.getForInstance(o.plugins);s.length=0,s.push(...we),A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,ae=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,de=o.features?.scrollToBottom??{};let Je=Yt();ee=o.features?.scrollBehavior??{},Je!==Yt()&&(as(),so()),rd(),rn();let vt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!vt){if(Ne||(fe=new Gs(he),Ne=new Ks(Re,fe),ze=ze??new Js,fe.open().then(()=>Ne?.restore()).catch(()=>{}),j.setSSEEventCallback((te,ot)=>{o.onSSEEvent?.(te,ot),ze?.processEvent(te,ot),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(ot)})})),!it&&D){let te=o.features?.eventStream?.classNames,ot="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:"");it=m("button",ot),it.style.width="28px",it.style.height="28px",it.style.color=Xt.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let Mt=oe("activity","18px","currentColor",1.5);Mt&&it.appendChild(Mt);let Xe=We.clearChatButtonWrapper,pt=We.closeButtonWrapper,Ut=Xe||pt;Ut&&Ut.parentNode===D?D.insertBefore(it,Ut):D.appendChild(it),it.addEventListener("click",()=>{Ae?Qr():tl()})}}else!Z&&vt&&(Qr(),it&&(it.remove(),it=null),Ne?.clear(),fe?.destroy(),Ne=null,fe=null,ze?.reset(),ze=null);if(o.launcher?.enabled===!1&&$t&&($t.destroy(),$t=null),o.launcher?.enabled===!1&&qt&&(qt.remove(),qt=null),o.launcher?.enabled!==!1&&!$t&&!qt){let{instance:te,element:ot}=vc({config:o,plugins:s,onToggle:_d});$t=te,te||(qt=ot),e.appendChild(ot)}$t&&$t.update(o),B&&o.launcher?.title!==void 0&&(B.textContent=o.launcher.title),J&&o.launcher?.subtitle!==void 0&&(J.textContent=o.launcher.subtitle);let lt=o.layout?.header;if(lt?.layout!==z&&D){let te=lt?$r(o,lt,{showClose:O(),onClose:()=>yt(!1,"user")}):Xn({config:o,showClose:O(),onClose:()=>yt(!1,"user")});st.replaceHeader(te),D=st.header.element,L=st.header.iconHolder,B=st.header.headerTitle,J=st.header.headerSubtitle,E=st.header.closeButton,z=lt?.layout}else if(lt&&(L&&(L.style.display=lt.showIcon===!1?"none":""),B&&(B.style.display=lt.showTitle===!1?"none":""),J&&(J.style.display=lt.showSubtitle===!1?"none":""),E&&(E.style.display=lt.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let te=lt.showClearChat;if(te!==void 0){We.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:ot}=We;ot&&!ot.classList.contains("persona-absolute")&&(te?ot.classList.remove("persona-ml-auto"):ot.classList.add("persona-ml-auto"))}}let Ot=o.layout?.showHeader!==!1;D&&(D.style.display=Ot?"":"none");let H=o.layout?.showFooter!==!1;q&&(q.style.display=H?"":"none"),dr(),rn(),A!==w?A?yt(W,"auto"):(U=!0,ps()):W!==N&&yt(W,"auto"),N=W,w=A,gs(),Jd();let Ue=JSON.stringify(l.toolCall)!==JSON.stringify(g),kt=JSON.stringify(o.messageActions)!==JSON.stringify(b),ft=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),Tt=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,xt=o.iterationDisplay!==Q,jt=(o.features?.showReasoning??!0)!==(_??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(Ue||kt||ft||Tt||xt||jt)&&j&&(ll++,is(xe,j.getMessages(),Oe));let gt=o.features?.streamAnimation?.type;if(gt!==se&&gt&&gt!=="none"){let te=_r(gt,o.features?.streamAnimation?.plugins);te&&Ai(te,e)}let ue=o.launcher??{},Et=ue.headerIconHidden??!1,Kt=o.layout?.header?.showIcon,Nt=Et||Kt===!1,at=ue.headerIconName,Ke=ue.headerIconSize??"48px";if(L){let te=ge.querySelector(".persona-border-b-persona-divider"),ot=te?.querySelector(".persona-flex-col");if(Nt)L.style.display="none",te&&ot&&!te.contains(ot)&&te.insertBefore(ot,te.firstChild);else{if(L.style.display="",L.style.height=Ke,L.style.width=Ke,te&&ot&&(te.contains(L)?L.nextSibling!==ot&&(L.remove(),te.insertBefore(L,ot)):te.insertBefore(L,ot)),at){let Xe=parseFloat(Ke)||24,pt=oe(at,Xe*.6,"currentColor",1);pt?L.replaceChildren(pt):L.textContent=ue.agentIconText??"\u{1F4AC}"}else if(ue.iconUrl){let Xe=L.querySelector("img");if(Xe)Xe.src=ue.iconUrl,Xe.style.height=Ke,Xe.style.width=Ke;else{let pt=document.createElement("img");pt.src=ue.iconUrl,pt.alt="",pt.className="persona-rounded-xl persona-object-cover",pt.style.height=Ke,pt.style.width=Ke,L.replaceChildren(pt)}}else{let Xe=L.querySelector("svg"),pt=L.querySelector("img");(Xe||pt)&&L.replaceChildren(),L.textContent=ue.agentIconText??"\u{1F4AC}"}let Mt=L.querySelector("img");Mt&&(Mt.style.height=Ke,Mt.style.width=Ke)}}let et=o.layout?.header?.showTitle,Rt=o.layout?.header?.showSubtitle;if(B&&(B.style.display=et===!1?"none":""),J&&(J.style.display=Rt===!1?"none":""),E){o.layout?.header?.showCloseButton===!1?E.style.display="none":E.style.display="";let ot=ue.closeButtonSize??"32px",Mt=ue.closeButtonPlacement??"inline";E.style.height=ot,E.style.width=ot;let{closeButtonWrapper:Xe}=We,pt=Mt==="top-right",Ut=Xe?.classList.contains("persona-absolute");if(Xe&&pt!==Ut)if(Xe.remove(),pt)Xe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(Xe);else{let Ve=ue.clearChat?.placement??"inline",_t=ue.clearChat?.enabled??!0;Xe.className=_t&&Ve==="inline"?"":"persona-ml-auto";let en=ge.querySelector(".persona-border-b-persona-divider");en&&en.appendChild(Xe)}if(E.style.color=ue.closeButtonColor||Xt.actionIconColor,ue.closeButtonBackgroundColor?(E.style.backgroundColor=ue.closeButtonBackgroundColor,E.classList.remove("hover:persona-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let Ve=ue.closeButtonBorderWidth||"0px",_t=ue.closeButtonBorderColor||"transparent";E.style.border=`${Ve} solid ${_t}`,E.classList.remove("persona-border-none")}else E.style.border="",E.classList.add("persona-border-none");ue.closeButtonBorderRadius?(E.style.borderRadius=ue.closeButtonBorderRadius,E.classList.remove("persona-rounded-full")):(E.style.borderRadius="",E.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(E.style.paddingLeft=ue.closeButtonPaddingX,E.style.paddingRight=ue.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),ue.closeButtonPaddingY?(E.style.paddingTop=ue.closeButtonPaddingY,E.style.paddingBottom=ue.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let an=ue.closeButtonIconName??"x",wn=ue.closeButtonIconText??"\xD7";E.innerHTML="";let Gt=oe(an,"28px","currentColor",1);Gt?E.appendChild(Gt):E.textContent=wn;let Pt=ue.closeButtonTooltipText??"Close chat",ln=ue.closeButtonShowTooltip??!0;if(E.setAttribute("aria-label",Pt),Xe&&(Xe._cleanupTooltip&&(Xe._cleanupTooltip(),delete Xe._cleanupTooltip),ln&&Pt)){let Ve=null,_t=()=>{if(Ve||!E)return;let Ko=E.ownerDocument,vs=Ko.body;if(!vs)return;Ve=In(Ko,"div","persona-clear-chat-tooltip"),Ve.textContent=Pt;let xs=In(Ko,"div");xs.className="persona-clear-chat-tooltip-arrow",Ve.appendChild(xs);let Go=E.getBoundingClientRect();Ve.style.position="fixed",Ve.style.zIndex=String(So),Ve.style.left=`${Go.left+Go.width/2}px`,Ve.style.top=`${Go.top-8}px`,Ve.style.transform="translate(-50%, -100%)",vs.appendChild(Ve)},en=()=>{Ve&&Ve.parentNode&&(Ve.parentNode.removeChild(Ve),Ve=null)};Xe.addEventListener("mouseenter",_t),Xe.addEventListener("mouseleave",en),E.addEventListener("focus",_t),E.addEventListener("blur",en),Xe._cleanupTooltip=()=>{en(),Xe&&(Xe.removeEventListener("mouseenter",_t),Xe.removeEventListener("mouseleave",en)),E&&(E.removeEventListener("focus",_t),E.removeEventListener("blur",en))}}}let{clearChatButton:De,clearChatButtonWrapper:tt}=We;if(De){let te=ue.clearChat??{},ot=te.enabled??!0,Mt=o.layout?.header?.showClearChat,Xe=Mt!==void 0?Mt:ot,pt=te.placement??"inline";if(tt){tt.style.display=Xe?"":"none";let{closeButtonWrapper:Ut}=We;!Y()&&Ut&&!Ut.classList.contains("persona-absolute")&&(Xe?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let an=pt==="top-right",wn=tt.classList.contains("persona-absolute");if(!Y()&&an!==wn&&Xe){if(tt.remove(),an)tt.className="persona-absolute persona-top-4 persona-z-50",tt.style.right="48px",ge.style.position="relative",ge.appendChild(tt);else{tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",tt.style.right="";let Pt=ge.querySelector(".persona-border-b-persona-divider"),ln=We.closeButtonWrapper;Pt&&ln&&ln.parentElement===Pt?Pt.insertBefore(tt,ln):Pt&&Pt.appendChild(tt)}let Gt=We.closeButtonWrapper;Gt&&!Gt.classList.contains("persona-absolute")&&(an?Gt.classList.add("persona-ml-auto"):Gt.classList.remove("persona-ml-auto"))}}if(Xe){if(!Y()){let Ve=te.size??"32px";De.style.height=Ve,De.style.width=Ve}let Ut=te.iconName??"refresh-cw",an=te.iconColor??"";De.style.color=an||Xt.actionIconColor,De.innerHTML="";let wn=Y()?"14px":"20px",Gt=oe(Ut,wn,"currentColor",2);if(Gt&&De.appendChild(Gt),te.backgroundColor?(De.style.backgroundColor=te.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let Ve=te.borderWidth||"0px",_t=te.borderColor||"transparent";De.style.border=`${Ve} solid ${_t}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");te.borderRadius?(De.style.borderRadius=te.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),te.paddingX?(De.style.paddingLeft=te.paddingX,De.style.paddingRight=te.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),te.paddingY?(De.style.paddingTop=te.paddingY,De.style.paddingBottom=te.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Pt=te.tooltipText??"Clear chat",ln=te.showTooltip??!0;if(De.setAttribute("aria-label",Pt),tt&&(tt._cleanupTooltip&&(tt._cleanupTooltip(),delete tt._cleanupTooltip),ln&&Pt)){let Ve=null,_t=()=>{if(Ve||!De)return;let Ko=De.ownerDocument,vs=Ko.body;if(!vs)return;Ve=In(Ko,"div","persona-clear-chat-tooltip"),Ve.textContent=Pt;let xs=In(Ko,"div");xs.className="persona-clear-chat-tooltip-arrow",Ve.appendChild(xs);let Go=De.getBoundingClientRect();Ve.style.position="fixed",Ve.style.zIndex=String(So),Ve.style.left=`${Go.left+Go.width/2}px`,Ve.style.top=`${Go.top-8}px`,Ve.style.transform="translate(-50%, -100%)",vs.appendChild(Ve)},en=()=>{Ve&&Ve.parentNode&&(Ve.parentNode.removeChild(Ve),Ve=null)};tt.addEventListener("mouseenter",_t),tt.addEventListener("mouseleave",en),De.addEventListener("focus",_t),De.addEventListener("blur",en),tt._cleanupTooltip=()=>{en(),tt&&(tt.removeEventListener("mouseenter",_t),tt.removeEventListener("mouseleave",en)),De&&(De.removeEventListener("focus",_t),De.removeEventListener("blur",en))}}}}let sn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zs],zo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[cr.message,cr.messageAndClick];I=ea({parsers:sn,handlers:zo,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),Oe=Qf(o,I,Me),j.updateConfig(o),is(xe,j.getMessages(),Oe),il(),Rd(),bl(j.isStreaming());let ip=o.voiceRecognition?.enabled===!0,Ta=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),It=o.voiceRecognition?.provider?.type==="runtype";if(ip&&(Ta||It))if(!K||!qe){let te=Am(o.voiceRecognition,o.sendButton);te&&(K=te.micButton,qe=te.micButtonWrapper,nt.insertBefore(qe,_e),K.addEventListener("click",Aa),K.disabled=j.isStreaming())}else{let te=o.voiceRecognition??{},ot=o.sendButton??{},Mt=te.iconName??"mic",Xe=ot.size??"40px",pt=te.iconSize??Xe,Ut=parseFloat(pt)||24;K.style.width=pt,K.style.height=pt,K.style.minWidth=pt,K.style.minHeight=pt;let an=te.iconColor??ot.textColor??"currentColor";K.innerHTML="";let wn=oe(Mt,Ut,an,2);wn?K.appendChild(wn):K.textContent="\u{1F3A4}";let Gt=te.backgroundColor??ot.backgroundColor;Gt?K.style.backgroundColor=Gt:K.style.backgroundColor="",an?K.style.color=an:K.style.color="var(--persona-text, #111827)",te.borderWidth?(K.style.borderWidth=te.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),te.borderColor?K.style.borderColor=te.borderColor:K.style.borderColor="",te.paddingX?(K.style.paddingLeft=te.paddingX,K.style.paddingRight=te.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),te.paddingY?(K.style.paddingTop=te.paddingY,K.style.paddingBottom=te.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Pt=qe?.querySelector(".persona-send-button-tooltip"),ln=te.tooltipText??"Start voice recognition";if((te.showTooltip??!1)&&ln)if(Pt)Pt.textContent=ln,Pt.style.display="";else{let _t=document.createElement("div");_t.className="persona-send-button-tooltip",_t.textContent=ln,qe?.insertBefore(_t,K)}else Pt&&(Pt.style.display="none");qe.style.display="",K.disabled=j.isStreaming()}else K&&qe&&(qe.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?j.isVoiceActive()&&j.toggleVoice():Pn&&io());if(o.attachments?.enabled===!0)if(!Be||!He){let te=o.attachments??{},Mt=(o.sendButton??{}).size??"40px";Ye||(Ye=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ye.style.display="none",Te.insertBefore(Ye,F)),Le||(Le=document.createElement("input"),Le.type="file",Le.accept=(te.allowedTypes??Kn).join(","),Le.multiple=(te.maxFiles??4)>1,Le.style.display="none",Le.setAttribute("aria-label","Attach files"),Te.insertBefore(Le,F)),Be=m("div","persona-send-button-wrapper"),He=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),He.type="button",He.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let Xe=te.buttonIconName??"paperclip",pt=Mt,Ut=parseFloat(pt)||40,an=Math.round(Ut*.6);He.style.width=pt,He.style.height=pt,He.style.minWidth=pt,He.style.minHeight=pt,He.style.fontSize="18px",He.style.lineHeight="1";let wn=oe(Xe,an,"currentColor",1.5);wn?He.appendChild(wn):He.textContent="\u{1F4CE}",He.addEventListener("click",ln=>{ln.preventDefault(),Le?.click()}),Be.appendChild(He);let Gt=te.buttonTooltipText??"Attach file",Pt=m("div","persona-send-button-tooltip");Pt.textContent=Gt,Be.appendChild(Pt),Ee?Ee.append(Be):Te.appendChild(Be),!Lt&&Le&&Ye&&(Lt=tr.fromConfig(te),Lt.setPreviewsContainer(Ye),Le.addEventListener("change",async()=>{Lt&&Le?.files&&(await Lt.handleFileSelect(Le.files),Le.value="")})),ge.querySelector(".persona-attachment-drop-overlay")||ge.appendChild(Yf(te.dropOverlay))}else{Be.style.display="";let te=o.attachments??{};Le&&(Le.accept=(te.allowedTypes??Kn).join(","),Le.multiple=(te.maxFiles??4)>1),Lt&&Lt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else Be&&(Be.style.display="none"),Lt&&Lt.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},hs=Ft.useIcon??!1,Ma=Ft.iconText??"\u2191",Cr=Ft.iconName,ys=Ft.tooltipText??"Send message",Rl=Ft.showTooltip??!1,qo=Ft.size??"40px",$n=Ft.backgroundColor,Vo=Ft.textColor;if(hs){if(ne.style.width=qo,ne.style.height=qo,ne.style.minWidth=qo,ne.style.minHeight=qo,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.innerHTML="",Vo?ne.style.color=Vo:ne.style.color="var(--persona-button-primary-fg, #ffffff)",Cr){let te=parseFloat(qo)||24,ot=Vo?.trim()||"currentColor",Mt=oe(Cr,te,ot,2);Mt?ne.appendChild(Mt):ne.textContent=Ma}else ne.textContent=Ma;ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n?(ne.style.backgroundColor=$n,ne.classList.remove("persona-bg-persona-primary")):(ne.style.backgroundColor="",ne.classList.add("persona-bg-persona-primary"))}else ne.textContent=o.copy?.sendButtonLabel??"Send",ne.style.width="",ne.style.height="",ne.style.minWidth="",ne.style.minHeight="",ne.style.fontSize="",ne.style.lineHeight="",ne.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",$n?(ne.style.backgroundColor=$n,ne.classList.remove("persona-bg-persona-accent")):ne.classList.add("persona-bg-persona-accent"),Vo?ne.style.color=Vo:ne.classList.add("persona-text-white");Ft.borderWidth?(ne.style.borderWidth=Ft.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Ft.borderColor?ne.style.borderColor=Ft.borderColor:ne.style.borderColor="",Ft.paddingX?(ne.style.paddingLeft=Ft.paddingX,ne.style.paddingRight=Ft.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Ft.paddingY?(ne.style.paddingTop=Ft.paddingY,ne.style.paddingBottom=Ft.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let bs=_e?.querySelector(".persona-send-button-tooltip");if(Rl&&ys)if(bs)bs.textContent=ys,bs.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=ys,_e?.insertBefore(te,ne)}else bs&&(bs.style.display="none");let ka=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ka?(xe.style.maxWidth=ka,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",Te&&(Te.style.maxWidth=ka,Te.style.marginLeft="auto",Te.style.marginRight="auto"),wt&&(wt.style.maxWidth=ka,wt.style.marginLeft="auto",wt.style.marginRight="auto")):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",Te&&(Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight=""),wt&&(wt.style.maxWidth="",wt.style.marginLeft="",wt.style.marginRight=""));let co=o.statusIndicator??{},Pm=co.visible??!0;if(k.style.display=Pm?"":"none",j){let te=j.getStatus();bt(k,(Mt=>Mt==="idle"?co.idleText??Dt.idle:Mt==="connecting"?co.connectingText??Dt.connecting:Mt==="connected"?co.connectedText??Dt.connected:Mt==="error"?co.errorText??Dt.error:Dt[Mt])(te),co,te)}k.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Rm=co.align==="left"?"persona-text-left":co.align==="center"?"persona-text-center":"persona-text-right";k.classList.add(Rm)},open(){O()&&yt(!0,"api")},close(){O()&&yt(!1,"api")},toggle(){O()&&yt(!U,"api")},reconnect(){j.reconnectNow()},clearChat(){Dn=!1,j.clearMessages(),No.clear(),so();try{localStorage.removeItem(Gr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Gr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&gl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),Ne?.clear(),ze?.reset(),Fe?.update()},setMessage(l){return!F||j.isStreaming()?!1:(!U&&O()&&yt(!0,"system"),F.value=l,F.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(j.isStreaming())return!1;let g=l?.trim()||F.value.trim();return g?(!U&&O()&&yt(!0,"system"),F.value="",F.style.height="auto",j.sendMessage(g),!0):!1},startVoiceRecognition(){return j.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(j.isVoiceActive()||(!U&&O()&&yt(!0,"system"),Qe.manuallyDeactivated=!1,Cn(),j.toggleVoice().then(()=>{Qe.active=j.isVoiceActive(),Nn("user"),j.isVoiceActive()&&vr()})),!0):Pn?!0:Fd()?(!U&&O()&&yt(!0,"system"),Qe.manuallyDeactivated=!1,Cn(),Ca("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?j.isVoiceActive()?(j.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,Cn(),Nn("user"),_n()}),!0):!1:Pn?(Qe.manuallyDeactivated=!0,Cn(),io("user"),!0):!1},injectMessage(l){return!U&&O()&&yt(!0,"system"),j.injectMessage(l)},injectAssistantMessage(l){!U&&O()&&yt(!0,"system");let g=j.injectAssistantMessage(l);return me&&(me=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)),g},injectUserMessage(l){return!U&&O()&&yt(!0,"system"),j.injectUserMessage(l)},injectSystemMessage(l){return!U&&O()&&yt(!0,"system"),j.injectSystemMessage(l)},injectMessageBatch(l){return!U&&O()&&yt(!0,"system"),j.injectMessageBatch(l)},injectComponentDirective(l){return!U&&O()&&yt(!0,"system"),j.injectComponentDirective(l)},injectTestMessage(l){!U&&O()&&yt(!0,"system"),j.injectTestEvent(l)},async connectStream(l,g){return j.connectStream(l,g)},__pushEventStreamEvent(l){Ne&&(ze?.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||tl()},hideEventStream(){Ae&&Qr()},isEventStreamVisible(){return Ae},showArtifacts(){Qt(o)&&(Dn=!1,pr=!0,On(),Ze?.setMobileOpen(!0))},hideArtifacts(){Qt(o)&&(Dn=!0,On())},upsertArtifact(l){return Qt(o)?(Xo(o.features?.artifacts,l.artifactType)==="panel"&&(Dn=!1,pr=!0),j.upsertArtifact(l)):null},selectArtifact(l){Qt(o)&&j.selectArtifact(l)},clearArtifacts(){Qt(o)&&j.clearArtifacts()},getArtifacts(){return j?.getArtifacts()??[]},getSelectedArtifactId(){return j?.getSelectedArtifactId()??null},focusInput(){return A&&!U&&!Y()||!F?!1:(F.focus(),!0)},async resolveApproval(l,g,b){let T=j.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===l);if(!T?.approval)throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){j.resolveWebMcpApproval(T.id,g);return}return j.resolveApproval(T.approval,g,b)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,g){return i.on(l,g)},off(l,g){i.off(l,g)},isOpen(){return O()&&U},isVoiceActive(){return Qe.active},toggleReadAloud(l){j.toggleReadAloud(l)},stopReadAloud(){j.stopSpeaking()},getReadAloudState(l){return j.getReadAloudState(l)},onReadAloudChange(l){return j.onReadAloudChange(l)},getState(){return{open:O()&&U,launcherEnabled:A,voiceActive:Qe.active,streaming:j.isStreaming()}},showCSATFeedback(l){!U&&O()&&yt(!0,"system");let g=xe.querySelector(".persona-feedback-container");g&&g.remove();let b=$i({onSubmit:async(v,T)=>{j.isClientTokenMode()&&await j.submitCSATFeedback(v,T),l?.onSubmit?.(v,T)},onDismiss:l?.onDismiss,...l});xe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!U&&O()&&yt(!0,"system");let g=xe.querySelector(".persona-feedback-container");g&&g.remove();let b=ji({onSubmit:async(v,T)=>{j.isClientTokenMode()&&await j.submitNPSFeedback(v,T),l?.onSubmit?.(v,T)},onDismiss:l?.onDismiss,...l});xe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return j.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return j.submitNPSFeedback(l,g)},destroy(){wl(),$o!=null&&(clearInterval($o),$o=null),Ge.forEach(l=>l()),ke.remove(),ct?.remove(),$t?.destroy(),qt?.remove(),Oo&&E.removeEventListener("click",Oo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:Bt,getMessages:Bt.getMessages,getStatus:Bt.getStatus,getMetadata:Bt.getPersistentMetadata,updateMetadata:Bt.updatePersistentMetadata,clearHistory:()=>Bt.clearChat(),setVoiceActive:b=>b?Bt.startVoiceRecognition():Bt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ge.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=_=>{let G=_.detail;(!G?.instanceId||G.instanceId===l)&&Bt.focusInput()};if(window.addEventListener("persona:focusInput",g),Ge.push(()=>{window.removeEventListener("persona:focusInput",g)}),Z){let _=re=>{let pe=re.detail;(!pe?.instanceId||pe.instanceId===l)&&Bt.showEventStream()},G=re=>{let pe=re.detail;(!pe?.instanceId||pe.instanceId===l)&&Bt.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",G),Ge.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",G)})}let b=_=>{let G=_.detail;(!G?.instanceId||G.instanceId===l)&&Bt.showArtifacts()},v=_=>{let G=_.detail;(!G?.instanceId||G.instanceId===l)&&Bt.hideArtifacts()},T=_=>{let G=_.detail;G?.instanceId&&G.instanceId!==l||G?.artifact&&Bt.upsertArtifact(G.artifact)},R=_=>{let G=_.detail;G?.instanceId&&G.instanceId!==l||typeof G?.id=="string"&&Bt.selectArtifact(G.id)},Q=_=>{let G=_.detail;(!G?.instanceId||G.instanceId===l)&&Bt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",Q),Ge.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",Q)})}let gn=hv(o.persistState);if(gn&&O()){let l=yv(gn.storage),g=`${gn.keyPrefix}widget-open`,b=`${gn.keyPrefix}widget-voice`,v=`${gn.keyPrefix}widget-voice-mode`;if(l){let T=gn.persist?.openState&&l.getItem(g)==="true",R=gn.persist?.voiceState&&l.getItem(b)==="true",Q=gn.persist?.voiceState&&l.getItem(v)==="true";if(T&&setTimeout(()=>{Bt.open(),setTimeout(()=>{if(R||Q)Bt.startVoiceRecognition();else if(gn.persist?.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),gn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(g,"true")}),i.on("widget:closed",()=>{l.setItem(g,"false")})),gn.persist?.voiceState&&(i.on("voice:state",_=>{l.setItem(b,_.active?"true":"false")}),i.on("user:message",_=>{l.setItem(v,_.viaVoice?"true":"false")})),gn.clearOnChatClear){let _=()=>{l.removeItem(g),l.removeItem(b),l.removeItem(v)},G=()=>_();window.addEventListener("persona:clear-chat",G),Ge.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(y&&O()&&setTimeout(()=>{Bt.open()},0),hr(),!Gg){let l=Sr(()=>{j&&(ll++,No.clear(),is(xe,j.getMessages(),Oe))});Ge.push(l)}return Bt};var Zf=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},xv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Cv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},wv=(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 s=o.offsetHeight>0;o.style.height="100%";let r=o.offsetHeight>0;o.remove(),!(!s||r)&&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.")},eg=(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"},_c=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=""},tg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",_c(e)},Oc=e=>{e.style.transition=""},Nc=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=""},Fc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},qi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Av=(e,t,n,o,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Sv=(e,t,n,o,s,r)=>{let a=r?t:e;s==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Tv=e=>{let t=Co(e),n=t.components?.panel,o=(s,r)=>s==null||s===""?r:Jt(t,s)??s;return{inset:o(n?.inset,ri),canvasBackground:o(n?.canvasBackground,si)}},ng=(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},Ev=(e,t,n,o,s,r,a,i)=>{let p=tn(r),d=p.reveal==="push",c=i!=null,u=i?.inset??"",y=i?.canvasBackground??"";Av(e,t,n,o,d),Sv(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",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=r?.launcher?.mobileFullscreen??!0,C=r?.launcher?.mobileBreakpoint??640,M=f!=null?f.innerWidth<=C:!1;if(h&&M&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nc(t),Oc(o),tg(o),Fc(n),qi(s,o),ng(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(r?.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"),tg(o),xv(o,p.maxHeight),ng(o,c&&a,u,y),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Nc(t),Oc(o),Fc(n),qi(s,o);let I=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":A;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=I,o.style.transform=W,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",Oc(o),_c(o),qi(s,o);let I=Zf(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),W=p.animate?"margin-left 180ms ease":"none",$=p.side==="right"?a?-I:0:a?0:-I;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=`${A+I}px`,t.style.transition=W,t.style.marginLeft=`${$}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}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="",Nc(t),_c(o),Fc(n),qi(s,o);let I=p.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=a?p.width:"0px",W=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",$=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",Cv(o,p.maxHeight),o.style.overflow=I||$?"hidden":"visible",o.style.transition=W,I){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let N=c?`calc(${Zf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;s.style.width=N,s.style.minWidth=N,s.style.maxWidth=N,s.style.boxSizing="border-box"}}},Mv=(e,t)=>{let n=e.ownerDocument.createElement("div");return eg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){eg(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 s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let r=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 y=null,f=()=>{y?.disconnect(),y=null},h=null,C=()=>{h=t?.launcher?.detachedPanel===!0?Tv(t):null};C();let M=()=>{Ev(a,i,p,d,c,t,u,h)},P=null,I=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=Dr(()=>{C(),M()}))},A=()=>{f(),tn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{M()}),y.observe(a)))},W=!1,$=()=>{M(),A(),u&&!W&&a.dataset.personaDockMobileFullscreen!=="true"&&(W=!0,wv(a,tn(t)))},N=a.ownerDocument.defaultView,w=()=>{$()};return N?.addEventListener("resize",w),tn(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),$(),I(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let V=z.launcherEnabled?z.open:!0;u!==V&&(u=V,$())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),$(),I()},destroy(){N?.removeEventListener("resize",w),P?.(),P=null,f(),o.isConnected&&(r&&r.parentNode===o?o.insertBefore(e,r):o.appendChild(e)),a.remove()}}},na=(e,t)=>Wt(t)?kv(e,t):Mv(e,t);var Lv=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},og=(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)},$c=e=>{let t=Lv(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,s=e.config,r=na(t,s),a,i=[],p=(M,P)=>{let A=!(P?.launcher?.enabled??!0)||Wt(P),W=o.createElement("div");if(W.setAttribute("data-persona-root","true"),A&&(W.style.height="100%",W.style.display="flex",W.style.flexDirection="column",W.style.flex="1",W.style.minHeight="0"),n){let $=M.attachShadow({mode:"open"});$.appendChild(W),og($,o)}else M.appendChild(W),og(M,o);return t.id&&W.setAttribute("data-persona-instance",t.id),W},d=()=>{r.syncWidgetState(a.getState())},c=()=>{i.forEach(M=>M()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let M=p(r.host,s);a=zi(M,s,{debugTools:e.debugTools}),c()},y=()=>{i.forEach(M=>M()),i=[],a.destroy()};u(),e.onChatReady?.();let f=M=>{y(),r.destroy(),r=na(t,M),s=M,u()},h={update(M){let P={...s,...M,launcher:{...s?.launcher??{},...M?.launcher??{},dock:{...s?.launcher?.dock??{},...M?.launcher?.dock??{}}}},I=Wt(s),A=Wt(P),W=Lo(s),$=Lo(P);if(I!==A||W!==$){f(P);return}s=P,r.updateConfig(s),a.update(M),d()},destroy(){y(),r.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(h,{get(M,P,I){if(P==="host")return r.host;if(P in M)return Reflect.get(M,P,I);let A=a[P];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function Pv(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 Rv(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(r=>r.toLowerCase().startsWith(o))?1:Pv(o,n)?2:3}function rg(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Vi(e,t){let n=t.trim();if(!n)return[...e].sort(rg);let o=[];for(let s of e){let r=Rv(s.label,n);r!==3&&o.push({item:s,tier:r})}return o.sort((s,r)=>s.tier!==r.tier?s.tier-r.tier:rg(s.item,r.item)),o.map(s=>s.item)}function Iv(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 sg(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Vi(e.items,t),resolve:e.resolve}}function ag(e){let t=e.commands.map(s=>({id:s.name,label:s.name,description:s.description,iconName:s.iconName,command:s.kind??"prompt",insertMode:s.insertMode,submitOnSelect:s.submitOnSelect,action:s.action,commandArgsPlaceholder:s.argsPlaceholder})),n=new Map(e.commands.map(s=>[s.name,s])),o=new Map(t.map(s=>[s.id,s]));return{id:e.id,label:e.label,matchCommand:s=>o.get(s),resolveOn:"submit",search:s=>Vi(t,Iv(s).name),resolve:(s,r)=>{let a=n.get(s.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(r.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(r.args):a.prompt??""}:{}}}}var pg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Wv=new Set(["button","a","input","select","textarea","details","summary"]),Hv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),jc=/\b(product|card|item|listing|result)\b/i,zc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Bv=3e3,Dv=100;function ug(e){let t=typeof e.className=="string"?e.className:"";if(jc.test(t)||e.id&&jc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&jc.test(o.value))return!0}return!1}function fg(e){return zc.test((e.textContent??"").trim())}function gg(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 Ov(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ig(e){let t=e.match(zc);return t?t[0]:null}function lg(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 Nv(e){let t=[],n=o=>{let s=o.trim();s&&!t.includes(s)&&t.push(s)};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 Fv="commerce-card",_v="result-card";function cg(e){return!ug(e)||!fg(e)||!gg(e)&&!Ov(e)?0:5200}function dg(e){return!ug(e)||fg(e)||!gg(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var qc=[{id:Fv,scoreElement(e){return cg(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||zc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(cg(e)===0)return null;let{title:n,href:o}=lg(e),s=ig((e.textContent??"").trim())??ig(t.text)??"",r=Nv(e);return[o&&n?`[${n}](${o})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,r.length?`actions: ${r.join(", ")}`:""].filter(Boolean).join(`
143
- `)}},{id:_v,scoreElement(e){return dg(e)},formatSummary(e,t){if(dg(e)===0)return null;let{title:n,href:o}=lg(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
- `)}}];function $v(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function jv(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",s=t.maxTextLength??e.maxTextLength??200,r=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??qc;return i==="simple"&&e.rules&&e.rules.length>0?($v(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:s,visibleOnly:r,root:a,rules:d}}function Uc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Uv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function zv(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"||Wv.has(t)||n&&Hv.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function mg(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 qv(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let r=e.getAttribute("type");r&&(t.type=r);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 Vc(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Uc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Uv){let r=e.getAttribute(s);if(r){let a=`${t}[${s}="${Uc(r)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Uc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let r=e.parentElement;if(r){let i=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Vv(e){return e==="static"?Dv:Bv}function hg(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Vc(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:zv(e),attributes:qv(e)}}function Kv(e,t,n,o){let s=Vv(t.interactivity),r=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(s+=i,a.formatSummary&&!r&&(r=a))}return{score:s,formattingRule:r}}function Gv(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 Jv(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,s=[],r=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(pg.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!mg(d)){i=a.nextNode();continue}let u=hg(d,e.maxTextLength),y=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(M=>M==="role");if(!y&&!f){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:C}=Kv(d,u,e.rules,n);s.push({el:d,domIndex:r,enriched:u,score:h,formattingRule:C}),r+=1}i=a.nextNode()}s.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of s){if(p.length>=e.maxElements)break;Gv(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let y=d.formattingRule.formatSummary(d.el,d.enriched,n);y&&(c=y)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function Xv(e,t){let n=[],o=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),r=s.currentNode;for(;r&&n.length<e.maxElements;){if(r.nodeType===Node.ELEMENT_NODE){let p=r,d=p.tagName.toLowerCase();if(pg.has(d)){r=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){r=s.nextNode();continue}}catch{}if(e.visibleOnly&&!mg(p)){r=s.nextNode();continue}let c=hg(p,e.maxTextLength),u=c.text.length>0,y=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!y){r=s.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}r=s.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 yg(e={}){let t=jv(e),n=t.root??document.body;return n?t.mode==="simple"?Xv(t,n):Jv(t,n):[]}var Ki=100;function bg(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let r=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);r.length>0&&o.push(`Structured summaries:
145
- ${r.map(a=>`- ${a.split(`
141
+ ${st?"background: transparent !important;":""}
142
+ `}if(!x&&!l){let Rt="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",Ma=g?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;We.style.cssText+=Rt+Yt+Ma}zo()};ga(),nr(e,o),Qs(e,o),Ys(e,o),Zr=()=>{ga(),nr(e,o),Qs(e,o),Ys(e,o),ia?e.style.setProperty("--persona-artifact-welded-outer-radius",ia):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ge=[];Ge.push(()=>{document.removeEventListener("keydown",md)}),Ge.push(()=>{Xr!==null&&clearTimeout(Xr)});let kn=null,Ln=null;Ge.push(()=>{kn?.(),kn=null,Ln?.(),Ln=null}),Yr&&Ge.push(()=>{Yr?.disconnect(),Yr=null}),Ge.push(()=>{ns?.(),ns=null,il(),At&&(At.remove(),At=null),nt?.element.style.removeProperty("width"),nt?.element.style.removeProperty("maxWidth")}),Z&&Ge.push(()=>{Xe!==null&&(cancelAnimationFrame(Xe),Xe=null),Be?.destroy(),Be=null,Ne?.destroy(),Ne=null,ue=null});let Do=null,bd=()=>{Do&&(Do(),Do=null),o.colorScheme==="auto"&&(Do=Dr(()=>{nr(e,o)}))};bd(),Ge.push(()=>{Do&&(Do(),Do=null)}),Ge.push(a);let ma=o.features?.streamAnimation;if(ma?.type&&ma.type!=="none"){let l=_r(ma.type,ma.plugins);l&&(Ai(l,e),Ge.push(()=>gf(e)))}let ha=Bf(wt),Oo=null,j,ll=l=>{if(!j)return;let g=l??j.getMessages(),b=o.features?.suggestReplies?.enabled!==!1?_a(g):null;b?ha.render(b,j,be,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?ha.render([],j,be,g):ha.render(o.suggestionChips,j,be,g,o.suggestionChipsConfig)},vn=!1,No=tf(),gr=new Map,Fo=new Map,no=new Map,cl=0,Qg=jn()!==null,nn=yi(),dn=0,oo=null,pn=!1,ya=!1,ro=0,xn=null,_o=null,dl=!1,ba=!1,pl=null,os=!0,ul=!1,fl=null,Yg=4,va=24,Zg=80,gl=new Map,et={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},vd=o.voiceRecognition?.autoResume??!1,Nn=l=>{i.emit("voice:state",{active:et.active,source:l,timestamp:Date.now()})},Cn=()=>{C(l=>({...l,voiceState:{active:et.active,timestamp:Date.now(),manuallyDeactivated:et.manuallyDeactivated}}))},em=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=Oc(c.voiceState),g=!!l.active,b=Number(l.timestamp??0);et.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-b<hv&&setTimeout(()=>{et.active||(et.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?j.toggleVoice().then(()=>{et.active=j.isVoiceActive(),Nn("restore"),j.isVoiceActive()&&vr()}):wa("restore"))},1e3)},tm=()=>j?Zf(j.getMessages()).filter(l=>!l.__skipPersist):[],xa=null,xd=(l,g)=>{typeof console<"u"&&console.error(l,g)},ml=(l,g)=>{let b=()=>{try{let X=l();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(_=>{xd(g,_)})}catch(X){return xd(g,X),null}},x=xa,E=x?x.then(()=>b()??void 0):b();if(!E)return;let R=E.finally(()=>{xa===R&&(xa=null)});xa=R};function hl(l){if(!d?.save)return;let b={messages:l?Zf(l):j?tm():[],metadata:c,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};ml(()=>d.save(b),"[AgentWidget] Failed to persist state:")}let mr=null,Cd=()=>We.querySelector("#persona-scroll-container")||le,rs=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),pn=!1},wd=()=>{oo!==null&&(cancelAnimationFrame(oo),oo=null),ya=!1,rs()},nm=()=>vn&&bl()&&(Qt()!=="anchor-top"||nd()),yl=()=>{let l=Io()||"Jump to latest",g=nm();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),ro>0?(Wo.textContent=String(ro),Wo.style.display="",Wt.setAttribute("aria-label",`${l} (${ro} new)`)):(Wo.textContent="",Wo.style.display="none",Wt.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},Ad=()=>{ro!==0&&(ro=0,yl())},bl=()=>Yn()?!nn.isFollowing():!Mo(le,va),on=()=>{if(!sa()||Ue){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==ge&&ge.appendChild(Wt),dr();let g=Hn(le)>0&&bl();g?yl():Ad(),Wt.style.display=g?"":"none"},ss=()=>{nn.pause()&&(wd(),on())},so=()=>{nn.resume(),Ad(),on()},ao=(l=!1)=>{Yn()&&nn.isFollowing()&&(!l&&!vn||(oo!==null&&(cancelAnimationFrame(oo),oo=null),ya=!0,oo=requestAnimationFrame(()=>{oo=null,ya=!1,nn.isFollowing()&&om(Cd(),l?220:140)})))},Sd=(l,g,b,x=()=>!0)=>{let E=l.scrollTop,R=g(),X=R-E;if(rs(),Math.abs(X)<1){pn=!0,l.scrollTop=R,dn=l.scrollTop,pn=!1;return}let _=performance.now();pn=!0;let J=de=>1-Math.pow(1-de,3),se=de=>{if(!x()){rs();return}let ae=g();ae!==R&&(R=ae,X=R-E);let Ae=de-_,Je=Math.min(Ae/b,1),bt=J(Je),lt=E+X*bt;l.scrollTop=lt,dn=l.scrollTop,Je<1?mr=requestAnimationFrame(se):(l.scrollTop=R,dn=l.scrollTop,mr=null,pn=!1)};mr=requestAnimationFrame(se)},om=(l,g=500)=>{let b=Hn(l)-l.scrollTop;if(Math.abs(b)<1){dn=l.scrollTop;return}if(Math.abs(b)>=Zg){rs(),pn=!0,l.scrollTop=Hn(l),dn=l.scrollTop,pn=!1;return}Sd(l,()=>Hn(l),g,()=>nn.isFollowing())},Td=()=>{let l=Cd();pn=!0,l.scrollTop=Hn(l),dn=l.scrollTop,pn=!1,on()},Ed=l=>{let g=0,b=l;for(;b&&b!==le;)g+=b.offsetTop,b=b.offsetParent;return g},Md=()=>{if(zg()!=="last-user-turn")return!1;let l=j?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(R=>R.role==="user");if(!g)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=le.querySelector(`[data-message-id="${b}"]`);if(!x)return!1;let E=Math.min(Math.max(0,Ed(x)-ed()),Hn(le));return pn=!0,le.scrollTop=E,dn=le.scrollTop,pn=!1,Qt()==="follow"&&!Mo(le,va)&&nn.pause(),on(),!0},kd=l=>{Zn.style.height=`${Math.max(0,Math.round(l))}px`,xn&&(xn.spacerHeight=Math.max(0,l))},as=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),rs(),xn=null,Zn.style.height="0px"},rm=l=>{_o!==null&&cancelAnimationFrame(_o),_o=requestAnimationFrame(()=>{_o=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=le.querySelector(`[data-message-id="${g}"]`);if(!b)return;let x=Ed(b),E=xn?.spacerHeight??0,R=le.scrollHeight-E,{targetScrollTop:X,spacerHeight:_}=af({anchorOffsetTop:x,topOffset:ed(),viewportHeight:le.clientHeight,contentHeight:R});xn={initialSpacerHeight:_,contentHeightAtAnchor:R,spacerHeight:_},kd(_),Sd(le,()=>X,220)})},sm=()=>{if(Yn()){if(!nn.isFollowing()||Mo(le,1))return;ao(!vn);return}if(xn&&xn.initialSpacerHeight>0){let l=le.scrollHeight-xn.spacerHeight,g=lf({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:l});g!==xn.spacerHeight&&kd(g)}on()},am=l=>{let g=Qt();g==="follow"?(so(),ao(!0)):g==="anchor-top"&&(os=!1,ul=!0,rm(l))},im=()=>{if(Qt()==="anchor-top"){if(ul){os=!1;return}os=!0,as(),so(),ao(!0)}},lm=l=>{let g=new Map;l.forEach(b=>{let x=gl.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(i.emit("assistant:message",b),!ba&&(Qt()!=="anchor-top"||nd())&&bl()&&(ro+=1,yl(),on(),rd(ro===1?"1 new message below.":`${ro} new messages below.`))),b.role==="assistant"&&x?.streaming&&b.streaming===!1&&i.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&i.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):i.emit("approval:requested",{approval:b.approval,message:b}))}),gl.clear(),g.forEach((b,x)=>{gl.set(x,b)})},cm=(l,g,b)=>{let x=document.createElement("div"),R=(()=>{let H=r.find(_e=>_e.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(H,_e)=>_e==null?!1:typeof _e=="string"?(H.textContent=_e,!0):(H.appendChild(_e),!0),_=new Set,J=new Set,se=r.some(H=>H.renderAskUserQuestion),de=[],ae=[],Ae=o.enableComponentStreaming!==!1,Je=o.approval!==!1,bt=[];if(g.forEach(H=>{_.add(H.id);let _e=se&&zn(H),Se=Je&&H.variant==="approval"&&!!H.approval,$e=!_e&&H.role==="assistant"&&!H.variant&&Ae&&na(H);!Se&&no.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(H.id)),!$e&&Fo.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),Fo.delete(H.id));let Mt=zn(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=ef(H,cl)+Mt,Tt=_e||Se||$e?null:nf(No,H.id,ut);if(Tt){x.appendChild(Tt.cloneNode(!0)),zn(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(J.add(H.toolCall.id),Lr(H,o,Le.composerOverlay));return}let xt=null,jt=r.find(pe=>!!(H.variant==="reasoning"&&pe.renderReasoning||H.variant==="tool"&&pe.renderToolCall||!H.variant&&pe.renderMessage)),Uo=o.layout?.messages;if(zn(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){gr.delete(H.id),l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ms(H)&&o.features?.suggestReplies?.enabled!==!1)return;if(zn(H)&&o.features?.askUserQuestion?.enabled!==!1){let pe=r.find(Et=>typeof Et.renderAskUserQuestion=="function");if(pe&&mt.current){let Et=gr.get(H.id),Kt=Et!==ut,Ot=null;if(Kt){let{payload:ot,complete:Pt}=qn(H),De=H.id,rt=()=>mt.current?.getMessages().find(rn=>rn.id===De);Ot=pe.renderAskUserQuestion({message:H,payload:ot,complete:Pt,resolve:rn=>{let zo=rt();zo&&mt.current?.resolveAskUserQuestion(zo,rn)},dismiss:()=>{let rn=rt();rn?.agentMetadata?.awaitingLocalTool&&(mt.current?.markAskUserQuestionResolved(rn),mt.current?.resolveAskUserQuestion(rn,"(dismissed)"))},config:o})}let st=Et!=null;if(Kt&&Ot===null&&!st){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(J.add(H.toolCall.id),Lr(H,o,Le.composerOverlay));return}let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${H.id}`,Ve.setAttribute("data-wrapper-id",H.id),Ve.setAttribute("data-ask-plugin-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),x.appendChild(Ve),de.push({messageId:H.id,fingerprint:ut,bubble:Ot});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(J.add(H.toolCall.id),Lr(H,o,Le.composerOverlay));return}}else if(Se){let pe=r.find(st=>typeof st.renderApproval=="function")??s,Kt=no.get(H.id)!==ut,Ot=null;if(Kt&&pe?.renderApproval){let st=H.id,Ve=(ot,Pt)=>{let De=mt.current?.getMessages().find(rt=>rt.id===st);De?.approval&&(De.approval.toolType==="webmcp"?mt.current?.resolveWebMcpApproval(De.id,ot):mt.current?.resolveApproval(De.approval,ot,Pt))};Ot=pe.renderApproval({message:H,defaultRenderer:()=>Hi(H,o),config:o,approve:ot=>Ve("approved",ot),deny:ot=>Ve("denied",ot)})}if(Kt&&Ot===null)l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(H.id),xt=Hi(H,o);else{let st=document.createElement("div");st.className="persona-flex",st.id=`wrapper-${H.id}`,st.setAttribute("data-wrapper-id",H.id),st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),x.appendChild(st),bt.push({messageId:H.id,fingerprint:ut,bubble:Ot});return}}else if(jt)if(H.variant==="reasoning"&&H.reasoning&&jt.renderReasoning){if(!ie)return;xt=jt.renderReasoning({message:H,defaultRenderer:()=>Tc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&jt.renderToolCall){if(!xe)return;xt=jt.renderToolCall({message:H,defaultRenderer:()=>Mc(H,o),config:o})}else jt.renderMessage&&(xt=jt.renderMessage({message:H,defaultRenderer:()=>{let pe=Ur(H,b,Uo,o.messageActions,oe,{loadingIndicatorRenderer:R,widgetConfig:o});return H.role!=="user"&&Hc(pe,H,o,j),pe},config:o}));if(!xt&&$e){let pe=$i(H);if(pe){let Et=Fo.get(H.id),Kt=Et!==ut,Ot=o.wrapComponentDirectiveInBubble!==!1&&En.getOptions(pe.component)?.bubbleChrome!==!1,st=null;if(Kt){let Ve=_i(pe,{config:o,message:H,transform:b});if(Ve&&pe.component==="PersonaArtifactInline"){let ot=Ve.hasAttribute("data-artifact-inline")?Ve:Ve.querySelector("[data-artifact-inline]"),Pt=ot?.getAttribute("data-artifact-inline")??"",De=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Pt):Pt,rt=Pt?l.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${De}"]`)??null:null;ot&&rt&&rt!==ot&&Gu(rt)&&(ot===Ve?Ve=rt:ot.replaceWith(rt))}if(Ve)if(Ot){let ot=document.createElement("div");if(ot.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ot.id=`bubble-${H.id}`,ot.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Pt=document.createElement("div");Pt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Pt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ot.appendChild(Pt)}ot.appendChild(Ve),st=ot}else{let ot=document.createElement("div");if(ot.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ot.id=`bubble-${H.id}`,ot.setAttribute("data-message-id",H.id),ot.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Pt=document.createElement("div");Pt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Pt.innerHTML=b({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),ot.appendChild(Pt)}ot.appendChild(Ve),st=ot}}if(st||Et!=null){let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${H.id}`,Ve.setAttribute("data-wrapper-id",H.id),Ve.setAttribute("data-component-directive-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),Ot||Ve.classList.add("persona-w-full"),x.appendChild(Ve),ae.push({messageId:H.id,fingerprint:ut,bubble:st});return}}}if(!xt)if(H.variant==="reasoning"&&H.reasoning){if(!ie)return;xt=Tc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!xe)return;xt=Mc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;xt=Hi(H,o)}else{let pe=o.layout?.messages;pe?.renderUserMessage&&H.role==="user"?xt=pe.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):pe?.renderAssistantMessage&&H.role==="assistant"?xt=pe.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):xt=Ur(H,b,pe,o.messageActions,oe,{loadingIndicatorRenderer:R,widgetConfig:o}),H.role!=="user"&&xt&&Hc(xt,H,o,j)}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${H.id}`,ft.setAttribute("data-wrapper-id",H.id),H.role==="user"&&ft.classList.add("persona-justify-end"),xt?.getAttribute("data-persona-component-directive")==="true"&&ft.classList.add("persona-w-full"),ft.appendChild(xt),of(No,H.id,ut,ft),x.appendChild(ft)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(_e=>{let Se=_e.getAttribute("data-persona-ask-sheet-for");Se&&!J.has(Se)&&go(Le.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let H=[],_e=[];g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&xe){_e.push(Se);return}Se.variant==="reasoning"&&!ie||(_e.length>1&&H.push(_e),_e=[])}),_e.length>1&&H.push(_e),H.forEach((Se,$e)=>{let Mt=Se.map(Et=>Array.from(x.children).find(Kt=>Kt instanceof HTMLElement&&Kt.getAttribute("data-wrapper-id")===Et.id)).filter(Et=>!!Et);if(Mt.length<2)return;let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-tool-group-${$e}-${Se[0].id}`,ut.setAttribute("data-wrapper-id",`tool-group-${$e}-${Se[0].id}`);let Tt=document.createElement("div");Tt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Tt.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${Se.length} tools`,Uo=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Et=>Et.toolCall).filter(Et=>!!Et),defaultSummary:jt,config:o});X(xt,Uo)||(xt.textContent=jt);let ft=document.createElement("div");ft.className="persona-tool-group-stack persona-flex persona-flex-col";let pe=o.features?.toolCallDisplay?.groupedMode==="summary";Tt.appendChild(xt),pe||Tt.appendChild(ft),ut.appendChild(Tt),Mt[0].before(ut),Mt.forEach((Et,Kt)=>{if(pe){Et.remove();return}let Ot=document.createElement("div");Ot.className="persona-tool-group-item persona-relative",Ot.setAttribute("data-persona-tool-group-item","true"),Kt<Mt.length-1&&Ot.setAttribute("data-persona-tool-group-connector","true"),Ot.appendChild(Et),ft.appendChild(Ot)})})}rf(No,_);let lt=g.some(H=>H.role==="assistant"&&H.streaming),Vt=g[g.length-1],Dt=Vt?.role==="assistant"&&!Vt.streaming&&Vt.variant!=="approval";if(vn&&g.some(H=>H.role==="user")&&!lt&&!Dt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:sr},_e=r.find($e=>$e.renderLoadingIndicator),Se=null;if(_e?.renderLoadingIndicator&&(Se=_e.renderLoadingIndicator(H)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(H)),Se===null&&(Se=sr()),Se){let $e=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;$e.className=Mt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$e.setAttribute("data-typing-indicator","true"),$e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",$e.appendChild(Se);let ut=document.createElement("div");ut.className="persona-flex",ut.id="wrapper-typing-indicator",ut.setAttribute("data-wrapper-id","typing-indicator"),ut.appendChild($e),x.appendChild(ut)}}if(!vn&&g.length>0){let H=g[g.length-1],_e={config:o,lastMessage:H,messageCount:g.length},Se=r.find(Mt=>Mt.renderIdleIndicator),$e=null;if(Se?.renderIdleIndicator&&($e=Se.renderIdleIndicator(_e)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(_e)),$e){let Mt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Mt.className=ut?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild($e);let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id="wrapper-idle-indicator",Tt.setAttribute("data-wrapper-id","idle-indicator"),Tt.appendChild(Mt),x.appendChild(Tt)}}if(hi(l,x),de.length>0)for(let{messageId:H,fingerprint:_e,bubble:Se}of de){let $e=l.querySelector(`#wrapper-${H}`);$e&&Se!==null&&($e.replaceChildren(Se),$e.setAttribute("data-bubble-fp",_e),gr.set(H,_e))}if(gr.size>0)for(let H of gr.keys())_.has(H)||gr.delete(H);if(ae.length>0)for(let{messageId:H,fingerprint:_e,bubble:Se}of ae){let $e=l.querySelector(`#wrapper-${H}`);$e&&Se!==null&&($e.replaceChildren(Se),$e.setAttribute("data-bubble-fp",_e),Fo.set(H,_e))}if(Fo.size>0)for(let H of Fo.keys())_.has(H)||Fo.delete(H);if(bt.length>0)for(let{messageId:H,fingerprint:_e,bubble:Se}of bt){let $e=l.querySelector(`#wrapper-${H}`);$e&&Se!==null&&($e.replaceChildren(Se),$e.setAttribute("data-bubble-fp",_e),no.set(H,_e))}if(no.size>0)for(let H of no.keys())_.has(H)||no.delete(H)},is=(l,g,b)=>{cm(l,g,b),ud()},ls=null,dm=()=>{if(ls)return;let l=b=>{let x=b.composedPath();x.includes(We)||Ze&&x.includes(Ze)||ht(!1,"user")};ls=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Ld=()=>{if(!ls)return;(e.ownerDocument??document).removeEventListener("pointerdown",ls,!0),ls=null};Ge.push(()=>Ld());let cs=null,pm=()=>{if(cs)return;let l=b=>{b.key==="Escape"&&(b.isComposing||ht(!1,"user"))};cs=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Pd=()=>{if(!cs)return;(e.ownerDocument??document).removeEventListener("keydown",cs,!0),cs=null};Ge.push(()=>Pd());let ds=!1,Rd=new Set,um=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},hr=()=>{if(!Y())return;let l=Le.peekBanner,g=Le.peekTextNode;if(!l||!g)return;if(U){l.classList.remove("persona-pill-peek--visible");return}let b=j?.getMessages()??[],x;for(let Dt=b.length-1;Dt>=0;Dt--){let H=b[Dt];if(H.role==="assistant"&&H.content){x=H;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let E=x.content,R=!!x.streaming,X=um(),_=xi(X),J=_.type!=="none"?_r(_.type,X?.plugins):null,se=J?.isAnimating?.(x)===!0,de=J!==null&&(R||se);de&&J&&!Rd.has(J.name)&&(Ai(J,e),Rd.add(J.name));let ae=de&&J?.containerClass?J.containerClass:null,Ae=g.dataset.personaPeekStreamClass??null;Ae&&Ae!==ae&&(g.classList.remove(Ae),delete g.dataset.personaPeekStreamClass),ae&&Ae!==ae&&(g.classList.add(ae),g.dataset.personaPeekStreamClass=ae),de?(g.style.setProperty("--persona-stream-step",`${_.speed}ms`),g.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Je=de?Ci(E,_.buffer,J,x,R):E;if(de&&_.placeholder==="skeleton"&&R&&(!Je||!Je.trim())){let Dt=document.createElement("div"),H=qs();H.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(H),hi(g,Dt)}else{let Dt=Math.max(0,Je.length-100),H=Je.length>100?Je.slice(-100):Je,_e=Rn(H);if(!de||!J){let Se=Je.length>100?`\u2026${H}`:H;g.textContent!==Se&&(g.textContent=Se)}else{let Se=_e;(J.wrap==="char"||J.wrap==="word")&&(Se=zs(_e,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Dt}));let $e=document.createElement("div");if($e.innerHTML=Se,J.useCaret&&H.length>0){let Mt=wi(),ut=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),Tt=ut[ut.length-1];Tt?.parentNode?Tt.parentNode.insertBefore(Mt,Tt.nextSibling):$e.appendChild(Mt)}hi(g,$e),J.onAfterRender?.({container:g,bubble:l,messageId:x.id,message:x,speed:_.speed,duration:_.duration})}}let Vt=vn||ds;l.classList.toggle("persona-pill-peek--visible",Vt)};if(Y()){let l=Le.peekBanner;if(l){let x=E=>{E.preventDefault(),E.stopPropagation(),ht(!0,"user")};l.addEventListener("pointerdown",x),Ge.push(()=>{l.removeEventListener("pointerdown",x)})}let g=()=>{ds||(ds=!0,hr())},b=()=>{ds&&(ds=!1,hr())};ye.addEventListener("pointerenter",g),ye.addEventListener("pointerleave",b),Ge.push(()=>{ye.removeEventListener("pointerenter",g),ye.removeEventListener("pointerleave",b)}),Ze&&(Ze.addEventListener("pointerenter",g),Ze.addEventListener("pointerleave",b),Ge.push(()=>{Ze.removeEventListener("pointerenter",g),Ze.removeEventListener("pointerleave",b)}))}let fm=l=>{let g=o.launcher?.composerBar??{},b=g.expandedSize??"anchored",x=g.bottomOffset??"16px",E=g.collapsedMaxWidth,R=g.expandedMaxWidth??"880px",X=g.expandedTopOffset??"5vh",_=g.modalMaxWidth??"880px",J=g.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",de="var(--persona-pill-area-height, 80px)",ae=We.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Ze){let Ae=Ze.style;Ae.bottom=x,Ae.width=E??""}if(l&&b!=="fullscreen"){if(b==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=_,ae.maxWidth=se,ae.maxHeight=J,ae.height=J;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${x} + ${de})`,ae.top=X,ae.width=R,ae.maxWidth=se}},ps=()=>{if(!O())return;if(Y()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",de=U?"expanded":"collapsed";We.dataset.state=de,We.dataset.expandedSize=se,Ze&&(Ze.dataset.state=de,Ze.dataset.expandedSize=se),We.style.removeProperty("display"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),fm(U),ge.style.display=U?"flex":"none",ga(),U?(dm(),pm()):(Ld(),Pd()),hr();return}let l=It(o),g=e.ownerDocument.defaultView??window,b=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,E=g.innerWidth<=b,R=x&&E&&A,X=en(o).reveal;U?(We.style.removeProperty("display"),We.style.display=l?"flex":"",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),_t?_t.element.style.display="none":qt&&(qt.style.display="none")):(l?l&&(X==="overlay"||X==="push")&&!R?(We.style.removeProperty("display"),We.style.display="flex",We.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.setProperty("display","none","important"),We.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(We.style.display="",We.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),_t?_t.element.style.display=l?"none":"":qt&&(qt.style.display=l?"none":""))},ht=(l,g="user")=>{if(!O()||U===l)return;let b=U;U=l,ps();let x=(()=>{let R=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,_=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,se=X.innerWidth<=J,de=It(o)&&_&&se,ae=Y()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||_&&se&&A||de||ae})();if(U&&x){if(!kn){let R=e.getRootNode(),X=R instanceof ShadowRoot?R.host:e.closest(".persona-host");X&&(kn=gc(X,o.launcher?.zIndex??zt))}Ln||(Ln=mc(e.ownerDocument))}else U||(kn?.(),kn=null,Ln?.(),Ln=null);U&&(gs(),Md()||(Qt()==="follow"?ao(!0):Td()));let E={open:U,source:g,timestamp:Date.now()};U&&!b?i.emit("widget:opened",E):!U&&b&&i.emit("widget:closed",E),i.emit("widget:state",{open:U,launcherEnabled:A,voiceActive:et.active,streaming:j.isStreaming()})},vl=l=>{ct(l?"stop":"send"),G&&(G.disabled=l),ha.buttons.forEach(g=>{g.disabled=l}),z.dataset.personaComposerStreaming=l?"true":"false",z.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},xl=()=>{et.active||be&&be.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>xl(),200)});let Id=()=>{F.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",be.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let b=o.copy?.showWelcomeCard!==!1;l.style.display=b?"":"none",b?(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)&&!j?.isStreaming()&&(fe.textContent=o.copy?.sendButtonLabel??"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.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(g=>({...g,sessionId:l}))}});let $o=null,gm=()=>{$o==null&&($o=setInterval(()=>{let l=Ce.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval($o),$o=null;return}let g=Date.now();l.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=ja(g-x))})},100))},Cl=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((X,_)=>Cl(X,g[_]));let b=l,x=g,E=Object.keys(b),R=Object.keys(x);return E.length===R.length&&E.every(X=>Object.prototype.hasOwnProperty.call(x,X)&&Cl(b[X],x[X]))},Wd=l=>{let{content:g,rawContent:b,llmContent:x,...E}=l;return E},wl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!na(l),mm=(l,g,b)=>{if(l.length!==g.length)return!1;let x=l[b.index],E=g[b.index];return!x||!E||x.id!==b.id||E.id!==b.id?!1:(!Object.is(x.content,E.content)||!Object.is(x.rawContent,E.rawContent)||!Object.is(x.llmContent,E.llmContent))&&wl(x)&&wl(E)&&Cl(Wd(x),Wd(E))},Hd=null,yr=null,jo=null,Fn=null,Ca=l=>{Hd=l;let g,b;yr=null;for(let E=l.length-1;E>=0;E-=1){let R=l[E];if(!g&&R.role==="user"&&(g=R),!b&&R.role==="assistant"&&(b=R),!yr&&wl(R)&&(yr={index:E,id:R.id}),g&&b&&yr)break}is(Ce,l,Oe),lc(Ce,yn.artifacts,{suppressTransition:vn}),gm(),ll(l),ao(!vn),lm(l),l.length===0&&(as(),os=!0,ul=!1),!dl||ba?(dl=!0,pl=g?.id??null,fl=b?.id??null):g&&g.id!==pl?(pl=g.id,am(g.id)):b&&b.id!==fl&&im(),b&&(fl=b.id);let x=et.lastUserMessageId;g&&g.id!==x&&(et.lastUserMessageId=g.id,i.emit("user:message",g)),et.lastUserMessageWasVoice=!!g?.viaVoice,hl(l),hr()},Al=()=>{Fn!==null&&(cancelAnimationFrame(Fn),Fn=null);let l=jo;jo=null,l&&Ca(l)},Bd=()=>{Fn!==null&&cancelAnimationFrame(Fn),Fn=null,jo=null},hm=l=>{let g=jo??Hd;if(vn&&g&&yr&&mm(g,l,yr)){jo=l,Fn===null&&(Fn=requestAnimationFrame(()=>{Fn=null;let b=jo;jo=null,b&&Ca(b)}));return}if(l.length===0){Bd(),Ca(l);return}Al(),Ca(l)};j=new Hr(o,{onMessagesChanged(l){hm(l)},onStatusChanged(l){let g=o.statusIndicator??{};yt(k,(x=>x==="idle"?g.idleText??Bt.idle:x==="connecting"?g.connectingText??Bt.connecting:x==="connected"?g.connectedText??Bt.connected:x==="error"?g.errorText??Bt.error:x==="paused"?g.pausedText??Bt.paused:x==="resuming"?g.resumingText??Bt.resuming:Bt[x])(l),g,l)},onStreamingChanged(l){l||(j?.getMessages().length===0?Bd():Al()),vn=l,vl(l),j&&is(Ce,j.getMessages(),Oe),l||ao(!0),on(),rd(l?"Responding\u2026":"Response complete."),hr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":_n(),vr();break;case"processing":_n(),Mm();break;case"speaking":_n(),km();break;default:l==="idle"&&j.isBargeInActive()?(_n(),vr(),G?.setAttribute("aria-label","End voice session")):(et.active=!1,_n(),Nn("system"),Cn());break}},onArtifactsState(l){yn=l,l.artifacts.length===0&&(pr=!1),lc(Ce,l.artifacts,{suppressTransition:vn}),On(),hl()},onReconnect(l){let{executionId:g,lastEventId:b}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:g,after:b}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:g,after:b,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:g,after:b})}}),mt.current=j,Ge.push(()=>j.cancel());let Sl=null;if(j.onReadAloudChange((l,g)=>{dd=l,pd=g,ud();let b=l??Sl;l&&(Sl=l);let x=b?j.getMessages().find(E=>E.id===b)??null:null;i.emit("message:read-aloud",{messageId:b,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(Sl=null)}),dl=!0,o.voiceRecognition?.provider?.type==="runtype")try{j.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&j.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Ne||o.onSSEEvent)&&j.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),je?.processEvent(l,g),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let Dd=()=>{o.resume&&typeof o.reconnectStream=="function"&&j.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=Oc(l.metadata),I.syncFromMetadata()),l.messages?.length){ba=!0;try{j.hydrateMessages(l.messages)}finally{ba=!1}}l.artifacts?.length&&j.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Dd()):Dd();let Od=()=>{!Y()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ht(!0,"auto")},ym=(l,g)=>l?g?{refs:[...l.refs,...g.refs],finalize:async()=>{let[b,x]=await Promise.allSettled([l.finalize(),g.finalize()]),E=[];return b.status==="fulfilled"?E.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),x.status==="fulfilled"?E.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),Av(E)}}:l:g,bm=()=>{let g=be.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},us=!1,vm=async l=>{let g=be.value.trim(),b=kt?.hasAttachments()??!1,x=g?await(tn?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){be.value="",be.style.height="auto",fs(),tn?.clear();return}let E=tn?.collectForSubmit()??null,R=x?.kind==="server"?x.mentions:null,X=ym(E,R),_=x?.kind==="prompt"?x.sendText:g,J=!!E&&E.refs.length>0;if(!_&&!b&&!J&&!R)return;Od();let se;b&&(se=[],se.push(...kt.getContentParts()),_&&se.push(bo(_)));let de=x?.kind==="prompt"?void 0:bm();be.value="",be.style.height="auto",fs(),j.sendMessage(_,{contentParts:se,mentions:X??void 0,contentSegments:de,viaVoice:l?.viaVoice}),b&&kt.clearAttachments(),E&&tn?.clear()},Tl=async l=>{if(!us){us=!0;try{await vm(l)}finally{us=!1}}},Nd=l=>{if(l.preventDefault(),j.isStreaming()){j.cancel(),je?.reset(),Be?.update();return}us||Tl()},xm=()=>o.features?.composerHistory!==!1,El={...pc},Ml=!1,fs=()=>{El={...pc}},Cm=()=>j.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),wm=l=>{if(!be)return;Ml=!0,be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),Ml=!1;let g=be.value.length;be.setSelectionRange(g,g)},Am=l=>{Ml||(l.isComposing||tn?.handleInput(l.inputType??void 0),fs())},Sm=l=>{if(be&&!(!l.isComposing&&tn?.handleKeydown(l))){if(xm()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=be.selectionStart===0&&be.selectionEnd===0,b=Zu({direction:l.key==="ArrowUp"?"up":"down",history:Cm(),currentValue:be.value,atStart:g,state:El});if(El=b.state,b.handled){l.preventDefault(),b.value!==void 0&&wm(b.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(j.isStreaming()){l.preventDefault();return}if(us){l.preventDefault();return}fs(),l.preventDefault(),fe.click()}}},Fd=l=>{l.key!=="Escape"||l.isComposing||j.isStreaming()&&l.composedPath().includes(ge)&&(j.cancel(),je?.reset(),Be?.update(),fs(),l.preventDefault(),l.stopImmediatePropagation())},Tm=async l=>{if(o.attachments?.enabled!==!0||!kt)return;let g=vv(l.clipboardData);g.length!==0&&(l.preventDefault(),await kt.handleFiles(g))},un=null,Pn=!1,br=null,St=null,_d=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,wa=(l="user")=>{if(Pn||j.isStreaming())return;let g=_d();if(!g)return;un=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;un.continuous=!0,un.interimResults=!0,un.lang="en-US";let E=be.value;un.onresult=R=>{let X="",_="";for(let se=0;se<R.results.length;se++){let de=R.results[se],ae=de[0].transcript;de.isFinal?X+=ae+" ":_=ae}let J=E+X+_;be.value=J,br&&clearTimeout(br),(X||_)&&(br=window.setTimeout(()=>{be.value.trim()&&un&&Pn&&(io(),Tl({viaVoice:!0}))},x))},un.onerror=R=>{R.error!=="no-speech"&&io()},un.onend=()=>{if(Pn){let R=be.value.trim();R&&R!==E.trim()&&Tl({viaVoice:!0}),io()}};try{if(un.start(),Pn=!0,et.active=!0,l!=="system"&&(et.manuallyDeactivated=!1),Nn(l),Cn(),G){let R=o.voiceRecognition??{};St={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,_=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=_??"var(--persona-voice-recording-indicator, #ffffff)",_){let se=G.querySelector("svg");se&&se.setAttribute("stroke",_)}J&&(G.style.borderColor=J),G.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(l="user")=>{if(Pn){if(Pn=!1,br&&(clearTimeout(br),br=null),un){try{un.stop()}catch{}un=null}if(et.active=!1,Nn(l),Cn(),G){if(G.classList.remove("persona-voice-recording"),St){G.style.backgroundColor=St.backgroundColor,G.style.color=St.color,G.style.borderColor=St.borderColor;let g=G.querySelector("svg");g&&g.setAttribute("stroke",St.color||"currentColor"),St=null}G.setAttribute("aria-label","Start voice recognition")}}},Em=(l,g)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",E=l?.provider?.type==="custom";if(!(b||x||E))return null;let X=m("div","persona-send-button-wrapper"),_=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let J=l?.iconName??"mic",se=g?.size??"40px",de=l?.iconSize??se,ae=parseFloat(de)||24,Ae=l?.backgroundColor??g?.backgroundColor,Je=l?.iconColor??g?.textColor;_.style.width=de,_.style.height=de,_.style.minWidth=de,_.style.minHeight=de,_.style.fontSize="18px",_.style.lineHeight="1",Je?_.style.color=Je:_.style.color="var(--persona-text, #111827)";let lt=ne(J,ae,Je||"currentColor",1.5);lt?_.appendChild(lt):_.textContent="\u{1F3A4}",Ae?_.style.backgroundColor=Ae:_.style.backgroundColor="",l?.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l?.borderColor&&(_.style.borderColor=l.borderColor),l?.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l?.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),X.appendChild(_);let Vt=l?.tooltipText??"Start voice recognition";if((l?.showTooltip??!1)&&Vt){let H=m("div","persona-send-button-tooltip");H.textContent=Vt,X.appendChild(H)}return{micButton:_,micButtonWrapper:X}},kl=()=>{if(!G||St)return;let l=o.voiceRecognition??{};St={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}},Ll=(l,g)=>{if(!G)return;let b=G.querySelector("svg");b&&b.remove();let x=St?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),E=ne(l,x,g,1.5);E&&G.appendChild(E)},Aa=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},vr=()=>{if(!G)return;kl();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,b=l.recordingIconColor,x=l.recordingBorderColor;if(Aa(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let E=G.querySelector("svg");E&&E.setAttribute("stroke",b)}x&&(G.style.borderColor=x),G.setAttribute("aria-label","Stop voice recognition")},Mm=()=>{if(!G)return;kl();let l=o.voiceRecognition??{},g=j.getVoiceInterruptionMode(),b=l.processingIconName??"loader",x=l.processingIconColor??St?.color??"",E=l.processingBackgroundColor??St?.backgroundColor??"",R=l.processingBorderColor??St?.borderColor??"";Aa(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=E,G.style.borderColor=R;let X=x||"currentColor";G.style.color=X,Ll(b,X),G.setAttribute("aria-label","Processing voice input"),g==="none"&&(G.style.cursor="default")},km=()=>{if(!G)return;kl();let l=o.voiceRecognition??{},g=j.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=l.speakingIconName??b,E=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??St?.color??"":St?.color??""),R=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":St?.backgroundColor??""),X=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":St?.borderColor??"");Aa(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=R,G.style.borderColor=X;let _=E||"currentColor";G.style.color=_,Ll(x,_);let J=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",J),g==="none"&&(G.style.cursor="default"),g==="barge-in"&&G.classList.add("persona-voice-recording")},_n=()=>{G&&(Aa(),St&&(G.style.backgroundColor=St.backgroundColor??"",G.style.color=St.color??"",G.style.borderColor=St.borderColor??"",Ll(St.iconName,St.color||"currentColor"),St=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Sa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=j.getVoiceStatus(),g=j.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){j.stopVoicePlayback();return}if(j.isBargeInActive()){j.stopVoicePlayback(),j.deactivateBargeIn().then(()=>{et.active=!1,et.manuallyDeactivated=!0,Cn(),Nn("user"),_n()});return}j.toggleVoice().then(()=>{et.active=j.isVoiceActive(),et.manuallyDeactivated=!j.isVoiceActive(),Cn(),Nn("user"),j.isVoiceActive()?vr():_n()});return}if(Pn){let l=be.value.trim();et.manuallyDeactivated=!0,Cn(),io("user"),l&&(be.value="",be.style.height="auto",j.sendMessage(l))}else et.manuallyDeactivated=!1,Cn(),wa("user")};ad=Sa,G&&(G.addEventListener("click",Sa),Ge.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(j.isVoiceActive()&&j.toggleVoice(),_n()):io("system"),G&&G.removeEventListener("click",Sa)}));let Lm=i.on("assistant:complete",()=>{vd&&(et.active||et.manuallyDeactivated||vd==="assistant"&&!et.lastUserMessageWasVoice||setTimeout(()=>{!et.active&&!et.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?j.toggleVoice().then(()=>{et.active=j.isVoiceActive(),Nn("auto"),j.isVoiceActive()&&vr()}):wa("auto"))},600))});Ge.push(Lm);let Pm=i.on("action:resubmit",()=>{setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)});Ge.push(Pm);let $d=()=>{ht(!U,"user")},_t=null,qt=null;if(A&&!Y()){let{instance:l,element:g}=xc({config:o,plugins:r,onToggle:$d});_t=l,l||(qt=g)}_t?e.appendChild(_t.element):qt&&e.appendChild(qt),ps(),ll(),Id(),vl(j.isStreaming()),Md()||(Qt()==="follow"?ao(!0):Td()),em(),$&&(!A||Y()?setTimeout(()=>xl(),0):U&&setTimeout(()=>xl(),200));let gs=()=>{if(Y()){dr(),ps();return}let l=It(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,E=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640,X=x.innerWidth<=R,_=E&&X&&A;try{if(_){Zr(),es=fa();return}let J=!1;V&&(V=!1,Zr(),J=!0);let se=fa();if(!J&&se!==es&&(Zr(),J=!0),es=se,J&&al(),!A&&!l){ye.style.height="",ye.style.width="";return}if(!g&&!l){let ae=o?.launcher?.width??o?.launcherWidth??ln;ye.style.width=ae,ye.style.maxWidth=ae}if(ua(),!b){let de=x.innerHeight,ae=64,Ae=o.launcher?.heightOffset??0,Je=Math.max(200,de-ae),bt=Math.min(640,Je),lt=Math.max(200,bt-Ae);ye.style.height=`${lt}px`}}finally{if(dr(),ps(),U&&A){let se=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),de=o.launcher?.sidebarMode??!1,ae=o.launcher?.mobileFullscreen??!0,Ae=It(o)&&ae&&se,Je=de||ae&&se&&A||Ae;if(Je&&!Ln){let bt=e.getRootNode(),lt=bt instanceof ShadowRoot?bt.host:e.closest(".persona-host");lt&&!kn&&(kn=gc(lt,o.launcher?.zIndex??zt)),Ln=mc(e.ownerDocument)}else Je||(kn?.(),kn=null,Ln?.(),Ln=null)}}};gs();let jd=e.ownerDocument.defaultView??window;if(jd.addEventListener("resize",gs),Ge.push(()=>jd.removeEventListener("resize",gs)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{dr()});l.observe(z),Ge.push(()=>l.disconnect())}dn=le.scrollTop;let Ud=Hn(le),Rm=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},Pl=()=>sf(Rm(),le),zd=()=>{let l=le.scrollTop,g=Hn(le),b=g<Ud;if(Ud=g,!Yn()){dn=l,on();return}let{action:x,nextLastScrollTop:E}=bi({following:nn.isFollowing(),currentScrollTop:l,lastScrollTop:dn,nearBottom:Mo(le,va),userScrollThreshold:Yg,isAutoScrolling:pn||ya||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(dn=E,x==="resume"){Pl()||so();return}x==="pause"&&ss()};if(le.addEventListener("scroll",zd,{passive:!0}),Ge.push(()=>le.removeEventListener("scroll",zd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{sm()});l.observe(Ce),l.observe(le),Ge.push(()=>l.disconnect())}let qd=()=>{Yn()&&nn.isFollowing()&&Pl()&&ss()},Vd=le.ownerDocument;Vd.addEventListener("selectionchange",qd),Ge.push(()=>{Vd.removeEventListener("selectionchange",qd)});let Im=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Kd=l=>{td()&&Yn()&&nn.isFollowing()&&Im.has(l.key)&&ss()},Gd=l=>{if(!td()||!Yn()||!nn.isFollowing())return;let g=l.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&ss()};le.addEventListener("keydown",Kd),le.addEventListener("focusin",Gd),Ge.push(()=>{le.removeEventListener("keydown",Kd),le.removeEventListener("focusin",Gd)});let Jd=l=>{if(!Yn())return;let g=vi({following:nn.isFollowing(),deltaY:l.deltaY,nearBottom:Mo(le,va),resumeWhenNearBottom:!0});g==="pause"?ss():g==="resume"&&!Pl()&&so()};le.addEventListener("wheel",Jd,{passive:!0}),Ge.push(()=>le.removeEventListener("wheel",Jd)),Wt.addEventListener("click",()=>{as(),le.scrollTop=le.scrollHeight,dn=le.scrollTop,so(),ao(!0),on()}),Ge.push(()=>Wt.remove()),Ge.push(()=>{wd(),as()});let Xd=()=>{S&&(Oo&&(S.removeEventListener("click",Oo),Oo=null),O()?(S.style.display="",Oo=()=>{ht(!1,"user")},S.addEventListener("click",Oo)):S.style.display="none")};Xd(),(()=>{let{clearChatButton:l}=Le;l&&l.addEventListener("click",()=>{j.clearMessages(),No.clear(),so(),go(Le.composerOverlay);try{localStorage.removeItem(Gr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gr}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Gr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&ml(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),Ne?.clear(),je?.reset(),Be?.update()})})(),Q&&Q.addEventListener("submit",Nd);let Qd=[["keydown",Sm],["input",Am],["paste",Tm],["focus",Kg]],Yd=l=>{if(l)for(let[g,b]of Qd)l.addEventListener(g,b)},Zd=l=>{if(l)for(let[g,b]of Qd)l.removeEventListener(g,b)};Yd(be),tn?.onComposerSwap((l,g)=>{Zd(g),be=l,Yd(l)});let ep=e.ownerDocument??document;ep.addEventListener("keydown",Fd,!0);let tp="persona-attachment-drop-active",ms=0,Rl=()=>{ms=0,ge.classList.remove(tp)},xr=()=>o.attachments?.enabled===!0&&kt!==null,np=l=>{!zi(l.dataTransfer)||!xr()||(ms++,ms===1&&ge.classList.add(tp))},op=l=>{!zi(l.dataTransfer)||!xr()||(ms--,ms<=0&&Rl())},rp=l=>{!zi(l.dataTransfer)||!xr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},sp=l=>{if(!zi(l.dataTransfer)||!xr())return;l.preventDefault(),l.stopPropagation(),Rl();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&kt.handleFiles(g)},lo=!0;ge.addEventListener("dragenter",np,lo),ge.addEventListener("dragleave",op,lo),e.addEventListener("dragover",rp,lo),e.addEventListener("drop",sp,lo);let Ta=e.ownerDocument,ap=l=>{xr()&&l.preventDefault()},ip=l=>{xr()&&l.preventDefault()};Ta.addEventListener("dragover",ap),Ta.addEventListener("drop",ip),Ge.push(()=>{Q&&Q.removeEventListener("submit",Nd),Zd(be),ep.removeEventListener("keydown",Fd,!0),tn?.destroy()}),Ge.push(()=>{ge.removeEventListener("dragenter",np,lo),ge.removeEventListener("dragleave",op,lo),e.removeEventListener("dragover",rp,lo),e.removeEventListener("drop",sp,lo),Ta.removeEventListener("dragover",ap),Ta.removeEventListener("drop",ip),Rl()}),Ge.push(()=>{j.cancel()}),_t?Ge.push(()=>{_t?.destroy()}):qt&&Ge.push(()=>{qt?.remove()});let Ht={update(l){let g=o.toolCall,b=o.messageActions,x=o.layout?.messages,E=o.colorScheme,R=o.loadingIndicator,X=o.iterationDisplay,_=o.features?.showReasoning,J=o.features?.showToolCalls,se=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type;o=Oi(o,l),ga(),nr(e,o),Qs(e,o),Ys(e,o),On(),o.colorScheme!==E&&bd();let Ae=Zs.getForInstance(o.plugins);r.length=0,r.push(...Ae),A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,ie=o.features?.showReasoning??!0,xe=o.features?.showToolCalls??!0,ce=o.features?.scrollToBottom??{};let Je=Qt();ee=o.features?.scrollBehavior??{},Je!==Qt()&&(as(),so()),sd(),on();let bt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!bt){if(Ne||(ue=new Js(he),Ne=new Gs(Re,ue),je=je??new Xs,ue.open().then(()=>Ne?.restore()).catch(()=>{}),j.setSSEEventCallback((te,Ye)=>{o.onSSEEvent?.(te,Ye),je?.processEvent(te,Ye),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Ye)})})),!it&&D){let te=o.features?.eventStream?.classNames,Ye="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:"");it=m("button",Ye),it.style.width="28px",it.style.height="28px",it.style.color=Jt.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let vt=ne("activity","18px","currentColor",1.5);vt&&it.appendChild(vt);let Ke=Le.clearChatButtonWrapper,at=Le.closeButtonWrapper,Ut=Ke||at;Ut&&Ut.parentNode===D?D.insertBefore(it,Ut):D.appendChild(it),it.addEventListener("click",()=>{Ue?Qr():nl()})}}else!Z&&bt&&(Qr(),it&&(it.remove(),it=null),Ne?.clear(),ue?.destroy(),Ne=null,ue=null,je?.reset(),je=null);if(o.launcher?.enabled===!1&&_t&&(_t.destroy(),_t=null),o.launcher?.enabled===!1&&qt&&(qt.remove(),qt=null),o.launcher?.enabled!==!1&&!_t&&!qt){let{instance:te,element:Ye}=xc({config:o,plugins:r,onToggle:$d});_t=te,te||(qt=Ye),e.appendChild(Ye)}_t&&_t.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 lt=o.layout?.header;if(lt?.layout!==q&&D){let te=lt?$r(o,lt,{showClose:O(),onClose:()=>ht(!1,"user")}):Xn({config:o,showClose:O(),onClose:()=>ht(!1,"user")});pt.replaceHeader(te),D=pt.header.element,L=pt.header.iconHolder,B=pt.header.headerTitle,K=pt.header.headerSubtitle,S=pt.header.closeButton,q=lt?.layout}else if(lt){if(L&&(L.style.display=lt.showIcon===!1?"none":""),B&&(B.style.display=lt.showTitle===!1?"none":""),K&&(K.style.display=lt.showSubtitle===!1?"none":""),S){let te=O()&&lt.showCloseButton!==!1;S.style.display=te?"":"none"}if(Le.clearChatButtonWrapper){let te=lt.showClearChat;if(te!==void 0){Le.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Ye}=Le;Ye&&!Ye.classList.contains("persona-absolute")&&(te?Ye.classList.remove("persona-ml-auto"):Ye.classList.add("persona-ml-auto"))}}}let Dt=o.layout?.showHeader!==!1;D&&(D.style.display=Dt?"":"none");let H=o.layout?.showFooter!==!1;z&&(z.style.display=H?"":"none"),dr(),on(),A!==w?A?ht(W,"auto"):(U=!0,ps()):W!==N&&ht(W,"auto"),N=W,w=A,gs(),Xd();let $e=JSON.stringify(o.toolCall)!==JSON.stringify(g),Mt=JSON.stringify(o.messageActions)!==JSON.stringify(b),ut=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),Tt=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,xt=o.iterationDisplay!==X,jt=(o.features?.showReasoning??!0)!==(_??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);($e||Mt||ut||Tt||xt||jt)&&j&&(cl++,is(Ce,j.getMessages(),Oe));let ft=o.features?.streamAnimation?.type;if(ft!==ae&&ft&&ft!=="none"){let te=_r(ft,o.features?.streamAnimation?.plugins);te&&Ai(te,e)}let pe=o.launcher??{},Et=pe.headerIconHidden??!1,Kt=o.layout?.header?.showIcon,Ot=Et||Kt===!1,st=pe.headerIconName,Ve=pe.headerIconSize??"48px";if(L){let te=ge.querySelector(".persona-border-b-persona-divider"),Ye=te?.querySelector(".persona-flex-col");if(Ot)L.style.display="none",te&&Ye&&!te.contains(Ye)&&te.insertBefore(Ye,te.firstChild);else{if(L.style.display="",L.style.height=Ve,L.style.width=Ve,te&&Ye&&(te.contains(L)?L.nextSibling!==Ye&&(L.remove(),te.insertBefore(L,Ye)):te.insertBefore(L,Ye)),st){let Ke=parseFloat(Ve)||24,at=ne(st,Ke*.6,"currentColor",1);at?L.replaceChildren(at):L.textContent=pe.agentIconText??"\u{1F4AC}"}else if(pe.iconUrl){let Ke=L.querySelector("img");if(Ke)Ke.src=pe.iconUrl,Ke.style.height=Ve,Ke.style.width=Ve;else{let at=document.createElement("img");at.src=pe.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=Ve,at.style.width=Ve,L.replaceChildren(at)}}else{let Ke=L.querySelector("svg"),at=L.querySelector("img");(Ke||at)&&L.replaceChildren(),L.textContent=pe.agentIconText??"\u{1F4AC}"}let vt=L.querySelector("img");vt&&(vt.style.height=Ve,vt.style.width=Ve)}}let ot=o.layout?.header?.showTitle,Pt=o.layout?.header?.showSubtitle;if(B&&(B.style.display=ot===!1?"none":""),K&&(K.style.display=Pt===!1?"none":""),S){let te=O()&&o.layout?.header?.showCloseButton!==!1;S.style.display=te?"":"none";let Ye=pe.closeButtonSize??"32px",vt=pe.closeButtonPlacement??"inline";S.style.height=Ye,S.style.width=Ye;let{closeButtonWrapper:Ke}=Le,at=vt==="top-right",Ut=Ke?.classList.contains("persona-absolute");if(Ke&&at!==Ut)if(Ke.remove(),at)Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(Ke);else{let qe=pe.clearChat?.placement??"inline",Ft=pe.clearChat?.enabled??!0;Ke.className=Ft&&qe==="inline"?"":"persona-ml-auto";let Zt=ge.querySelector(".persona-border-b-persona-divider");Zt&&Zt.appendChild(Ke)}if(S.style.color=pe.closeButtonColor||Jt.actionIconColor,pe.closeButtonBackgroundColor?(S.style.backgroundColor=pe.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let qe=pe.closeButtonBorderWidth||"0px",Ft=pe.closeButtonBorderColor||"transparent";S.style.border=`${qe} solid ${Ft}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");pe.closeButtonBorderRadius?(S.style.borderRadius=pe.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(S.style.paddingLeft=pe.closeButtonPaddingX,S.style.paddingRight=pe.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),pe.closeButtonPaddingY?(S.style.paddingTop=pe.closeButtonPaddingY,S.style.paddingBottom=pe.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let sn=pe.closeButtonIconName??"x",wn=pe.closeButtonIconText??"\xD7";S.innerHTML="";let $t=ne(sn,"28px","currentColor",1);$t?($t.style.display="block",S.appendChild($t)):S.textContent=wn;let Lt=pe.closeButtonTooltipText??"Close chat",an=pe.closeButtonShowTooltip??!0;if(S.setAttribute("aria-label",Lt),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),an&&Lt)){let qe=null,Ft=()=>{if(qe||!S)return;let Ko=S.ownerDocument,vs=Ko.body;if(!vs)return;qe=In(Ko,"div","persona-clear-chat-tooltip"),qe.textContent=Lt;let xs=In(Ko,"div");xs.className="persona-clear-chat-tooltip-arrow",qe.appendChild(xs);let Go=S.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(So),qe.style.left=`${Go.left+Go.width/2}px`,qe.style.top=`${Go.top-8}px`,qe.style.transform="translate(-50%, -100%)",vs.appendChild(qe)},Zt=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};Ke.addEventListener("mouseenter",Ft),Ke.addEventListener("mouseleave",Zt),S.addEventListener("focus",Ft),S.addEventListener("blur",Zt),Ke._cleanupTooltip=()=>{Zt(),Ke&&(Ke.removeEventListener("mouseenter",Ft),Ke.removeEventListener("mouseleave",Zt)),S&&(S.removeEventListener("focus",Ft),S.removeEventListener("blur",Zt))}}}let{clearChatButton:De,clearChatButtonWrapper:rt}=Le;if(De){let te=pe.clearChat??{},Ye=te.enabled??!0,vt=o.layout?.header?.showClearChat,Ke=vt!==void 0?vt:Ye,at=te.placement??"inline";if(rt){rt.style.display=Ke?"":"none";let{closeButtonWrapper:Ut}=Le;!Y()&&Ut&&!Ut.classList.contains("persona-absolute")&&(Ke?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let sn=at==="top-right",wn=rt.classList.contains("persona-absolute");if(!Y()&&sn!==wn&&Ke){if(rt.remove(),sn)rt.className="persona-absolute persona-top-4 persona-z-50",rt.style.right="48px",ge.style.position="relative",ge.appendChild(rt);else{rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",rt.style.right="";let Lt=ge.querySelector(".persona-border-b-persona-divider"),an=Le.closeButtonWrapper;Lt&&an&&an.parentElement===Lt?Lt.insertBefore(rt,an):Lt&&Lt.appendChild(rt)}let $t=Le.closeButtonWrapper;$t&&!$t.classList.contains("persona-absolute")&&(sn?$t.classList.add("persona-ml-auto"):$t.classList.remove("persona-ml-auto"))}}if(Ke){if(!Y()){let qe=te.size??"32px";De.style.height=qe,De.style.width=qe}let Ut=te.iconName??"refresh-cw",sn=te.iconColor??"";De.style.color=sn||Jt.actionIconColor,De.innerHTML="";let wn=Y()?"14px":"20px",$t=ne(Ut,wn,"currentColor",1);if($t&&($t.style.display="block",De.appendChild($t)),te.backgroundColor?(De.style.backgroundColor=te.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let qe=te.borderWidth||"0px",Ft=te.borderColor||"transparent";De.style.border=`${qe} solid ${Ft}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");te.borderRadius?(De.style.borderRadius=te.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),te.paddingX?(De.style.paddingLeft=te.paddingX,De.style.paddingRight=te.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),te.paddingY?(De.style.paddingTop=te.paddingY,De.style.paddingBottom=te.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Lt=te.tooltipText??"Clear chat",an=te.showTooltip??!0;if(De.setAttribute("aria-label",Lt),rt&&(rt._cleanupTooltip&&(rt._cleanupTooltip(),delete rt._cleanupTooltip),an&&Lt)){let qe=null,Ft=()=>{if(qe||!De)return;let Ko=De.ownerDocument,vs=Ko.body;if(!vs)return;qe=In(Ko,"div","persona-clear-chat-tooltip"),qe.textContent=Lt;let xs=In(Ko,"div");xs.className="persona-clear-chat-tooltip-arrow",qe.appendChild(xs);let Go=De.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(So),qe.style.left=`${Go.left+Go.width/2}px`,qe.style.top=`${Go.top-8}px`,qe.style.transform="translate(-50%, -100%)",vs.appendChild(qe)},Zt=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};rt.addEventListener("mouseenter",Ft),rt.addEventListener("mouseleave",Zt),De.addEventListener("focus",Ft),De.addEventListener("blur",Zt),rt._cleanupTooltip=()=>{Zt(),rt&&(rt.removeEventListener("mouseenter",Ft),rt.removeEventListener("mouseleave",Zt)),De&&(De.removeEventListener("focus",Ft),De.removeEventListener("blur",Zt))}}}}let rn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ea],zo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[cr.message,cr.messageAndClick];I=ta({parsers:rn,handlers:zo,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),Oe=eg(o,I,Me),j.updateConfig(o),is(Ce,j.getMessages(),Oe),ll(),Id(),vl(j.isStreaming());let lp=o.voiceRecognition?.enabled===!0,Ea=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=o.voiceRecognition?.provider?.type==="runtype";if(lp&&(Ea||Rt))if(!G||!ze){let te=Em(o.voiceRecognition,o.sendButton);te&&(G=te.micButton,ze=te.micButtonWrapper,Qe.insertBefore(ze,hn),G.addEventListener("click",Sa),G.disabled=j.isStreaming())}else{let te=o.voiceRecognition??{},Ye=o.sendButton??{},vt=te.iconName??"mic",Ke=Ye.size??"40px",at=te.iconSize??Ke,Ut=parseFloat(at)||24;G.style.width=at,G.style.height=at,G.style.minWidth=at,G.style.minHeight=at;let sn=te.iconColor??Ye.textColor;G.innerHTML="";let wn=ne(vt,Ut,sn||"currentColor",1.5);wn?G.appendChild(wn):G.textContent="\u{1F3A4}";let $t=te.backgroundColor??Ye.backgroundColor;$t?G.style.backgroundColor=$t:G.style.backgroundColor="",sn?G.style.color=sn: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 Lt=ze?.querySelector(".persona-send-button-tooltip"),an=te.tooltipText??"Start voice recognition";if((te.showTooltip??!1)&&an)if(Lt)Lt.textContent=an,Lt.style.display="";else{let Ft=document.createElement("div");Ft.className="persona-send-button-tooltip",Ft.textContent=an,ze?.insertBefore(Ft,G)}else Lt&&(Lt.style.display="none");ze.style.display="",G.disabled=j.isStreaming()}else G&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?j.isVoiceActive()&&j.toggleVoice():Pn&&io());if(o.attachments?.enabled===!0){if(!He||!Ee){let te=o.attachments??{},vt=(o.sendButton??{}).size??"40px";tt||(tt=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),tt.style.display="none",Q.insertBefore(tt,be)),Pe||(Pe=document.createElement("input"),Pe.type="file",Pe.accept=(te.allowedTypes??Kn).join(","),Pe.multiple=(te.maxFiles??4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),Q.insertBefore(Pe,be)),He=m("div","persona-send-button-wrapper"),Ee=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ee.type="button",Ee.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let Ke=te.buttonIconName??"paperclip",at=vt,Ut=parseFloat(at)||40,sn=Math.round(Ut*.6);Ee.style.width=at,Ee.style.height=at,Ee.style.minWidth=at,Ee.style.minHeight=at,Ee.style.fontSize="18px",Ee.style.lineHeight="1";let wn=ne(Ke,sn,"currentColor",1.5);wn?Ee.appendChild(wn):Ee.textContent="\u{1F4CE}",Ee.addEventListener("click",an=>{an.preventDefault(),Pe?.click()}),He.appendChild(Ee);let $t=te.buttonTooltipText??"Attach file",Lt=m("div","persona-send-button-tooltip");Lt.textContent=$t,He.appendChild(Lt),Te?Te.append(He):Q.appendChild(He),!kt&&Pe&&tt&&(kt=tr.fromConfig(te),kt.setPreviewsContainer(tt),Pe.addEventListener("change",async()=>{kt&&Pe?.files&&(await kt.handleFileSelect(Pe.files),Pe.value="")}))}else{He.style.display="";let te=o.attachments??{};Pe&&(Pe.accept=(te.allowedTypes??Kn).join(","),Pe.multiple=(te.maxFiles??4)>1),kt&&kt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ge.querySelector(".persona-attachment-drop-overlay")?.remove(),ge.appendChild(tg(o.attachments?.dropOverlay)),Ee){let te=o.attachments??{},Ye=te.buttonTooltipText??"Attach file";Ee.setAttribute("aria-label",Ye),Ee.textContent="";let vt=parseFloat(o.sendButton?.size??"40px")||40,Ke=ne(te.buttonIconName??"paperclip",Math.round(vt*.6),"currentColor",1.5);Ke?Ee.appendChild(Ke):Ee.textContent="\u{1F4CE}";let at=He?.querySelector(".persona-send-button-tooltip");at&&(at.textContent=Ye)}}else He&&(He.style.display="none"),kt&&kt.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},hs=Nt.useIcon??!1,ka=Nt.iconText??"\u2191",Cr=Nt.iconName,ys=Nt.tooltipText??"Send message",Il=Nt.showTooltip??!1,qo=Nt.size??"40px",$n=Nt.backgroundColor,Vo=Nt.textColor;if(hs){if(fe.style.width=qo,fe.style.height=qo,fe.style.minWidth=qo,fe.style.minHeight=qo,fe.style.fontSize="18px",fe.style.lineHeight="1",Vo?fe.style.color=Vo:fe.style.color="var(--persona-button-primary-fg, #ffffff)",!j.isStreaming())if(fe.innerHTML="",Cr){let te=parseFloat(qo)||24,Ye=Vo?.trim()||"currentColor",vt=ne(Cr,te,Ye,2);vt?fe.appendChild(vt):fe.textContent=ka}else fe.textContent=ka;fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n?(fe.style.backgroundColor=$n,fe.classList.remove("persona-bg-persona-primary")):(fe.style.backgroundColor="",fe.classList.add("persona-bg-persona-primary"))}else fe.textContent=o.copy?.sendButtonLabel??"Send",fe.style.width="",fe.style.height="",fe.style.minWidth="",fe.style.minHeight="",fe.style.fontSize="",fe.style.lineHeight="",fe.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",$n?(fe.style.backgroundColor=$n,fe.classList.remove("persona-bg-persona-accent")):fe.classList.add("persona-bg-persona-accent"),Vo?fe.style.color=Vo:fe.classList.add("persona-text-white");Nt.borderWidth?(fe.style.borderWidth=Nt.borderWidth,fe.style.borderStyle="solid"):(fe.style.borderWidth="",fe.style.borderStyle=""),Nt.borderColor?fe.style.borderColor=Nt.borderColor:fe.style.borderColor="",Nt.paddingX?(fe.style.paddingLeft=Nt.paddingX,fe.style.paddingRight=Nt.paddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),Nt.paddingY?(fe.style.paddingTop=Nt.paddingY,fe.style.paddingBottom=Nt.paddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let bs=hn?.querySelector(".persona-send-button-tooltip");if(Il&&ys)if(bs)bs.textContent=ys,bs.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=ys,hn?.insertBefore(te,fe)}else bs&&(bs.style.display="none");let La=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);La?(Ce.style.maxWidth=La,Ce.style.marginLeft="auto",Ce.style.marginRight="auto",Ce.style.width="100%",Q&&(Q.style.maxWidth=La,Q.style.marginLeft="auto",Q.style.marginRight="auto"),wt&&(wt.style.maxWidth=La,wt.style.marginLeft="auto",wt.style.marginRight="auto")):(Ce.style.maxWidth="",Ce.style.marginLeft="",Ce.style.marginRight="",Ce.style.width="",Q&&(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight=""),wt&&(wt.style.maxWidth="",wt.style.marginLeft="",wt.style.marginRight=""));let co=o.statusIndicator??{},Wm=co.visible??!0;if(k.style.display=Wm?"":"none",j){let te=j.getStatus();yt(k,(vt=>vt==="idle"?co.idleText??Bt.idle:vt==="connecting"?co.connectingText??Bt.connecting:vt==="connected"?co.connectedText??Bt.connected:vt==="error"?co.errorText??Bt.error:Bt[vt])(te),co,te)}k.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hm=co.align==="left"?"persona-text-left":co.align==="center"?"persona-text-center":"persona-text-right";k.classList.add(Hm)},open(){O()&&ht(!0,"api")},close(){O()&&ht(!1,"api")},toggle(){O()&&ht(!U,"api")},reconnect(){j.reconnectNow()},clearChat(){Dn=!1,j.clearMessages(),No.clear(),so();try{localStorage.removeItem(Gr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Gr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&ml(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),Ne?.clear(),je?.reset(),Be?.update()},setMessage(l){return!be||j.isStreaming()?!1:(!U&&O()&&ht(!0,"system"),be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(j.isStreaming())return!1;let g=l?.trim()||be.value.trim();return g?(!U&&O()&&ht(!0,"system"),be.value="",be.style.height="auto",j.sendMessage(g),!0):!1},startVoiceRecognition(){return j.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(j.isVoiceActive()||(!U&&O()&&ht(!0,"system"),et.manuallyDeactivated=!1,Cn(),j.toggleVoice().then(()=>{et.active=j.isVoiceActive(),Nn("user"),j.isVoiceActive()&&vr()})),!0):Pn?!0:_d()?(!U&&O()&&ht(!0,"system"),et.manuallyDeactivated=!1,Cn(),wa("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?j.isVoiceActive()?(j.toggleVoice().then(()=>{et.active=!1,et.manuallyDeactivated=!0,Cn(),Nn("user"),_n()}),!0):!1:Pn?(et.manuallyDeactivated=!0,Cn(),io("user"),!0):!1},injectMessage(l){return!U&&O()&&ht(!0,"system"),j.injectMessage(l)},injectAssistantMessage(l){!U&&O()&&ht(!0,"system");let g=j.injectAssistantMessage(l);return me&&(me=!1,ve&&(clearTimeout(ve),ve=null),setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)),g},injectUserMessage(l){return!U&&O()&&ht(!0,"system"),j.injectUserMessage(l)},injectSystemMessage(l){return!U&&O()&&ht(!0,"system"),j.injectSystemMessage(l)},injectMessageBatch(l){return!U&&O()&&ht(!0,"system"),j.injectMessageBatch(l)},injectComponentDirective(l){return!U&&O()&&ht(!0,"system"),j.injectComponentDirective(l)},injectTestMessage(l){!U&&O()&&ht(!0,"system"),j.injectTestEvent(l)},async connectStream(l,g){return j.connectStream(l,g)},__pushEventStreamEvent(l){Ne&&(je?.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||nl()},hideEventStream(){Ue&&Qr()},isEventStreamVisible(){return Ue},showArtifacts(){Xt(o)&&(Dn=!1,pr=!0,On(),nt?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Dn=!0,On())},upsertArtifact(l){return Xt(o)?(Xo(o.features?.artifacts,l.artifactType)==="panel"&&(Dn=!1,pr=!0),j.upsertArtifact(l)):null},selectArtifact(l){Xt(o)&&j.selectArtifact(l)},clearArtifacts(){Xt(o)&&j.clearArtifacts()},getArtifacts(){return j?.getArtifacts()??[]},getSelectedArtifactId(){return j?.getSelectedArtifactId()??null},focusInput(){return A&&!U&&!Y()||!be?!1:(be.focus(),!0)},async resolveApproval(l,g,b){let E=j.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===l);if(!E?.approval)throw new Error(`Approval not found: ${l}`);if(E.approval.toolType==="webmcp"){j.resolveWebMcpApproval(E.id,g);return}return j.resolveApproval(E.approval,g,b)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,g){return i.on(l,g)},off(l,g){i.off(l,g)},isOpen(){return O()&&U},isVoiceActive(){return et.active},toggleReadAloud(l){j.toggleReadAloud(l)},stopReadAloud(){j.stopSpeaking()},getReadAloudState(l){return j.getReadAloudState(l)},onReadAloudChange(l){return j.onReadAloudChange(l)},getState(){return{open:O()&&U,launcherEnabled:A,voiceActive:et.active,streaming:j.isStreaming()}},showCSATFeedback(l){!U&&O()&&ht(!0,"system");let g=Ce.querySelector(".persona-feedback-container");g&&g.remove();let b=ji({onSubmit:async(x,E)=>{j.isClientTokenMode()&&await j.submitCSATFeedback(x,E),l?.onSubmit?.(x,E)},onDismiss:l?.onDismiss,...l});Ce.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!U&&O()&&ht(!0,"system");let g=Ce.querySelector(".persona-feedback-container");g&&g.remove();let b=Ui({onSubmit:async(x,E)=>{j.isClientTokenMode()&&await j.submitNPSFeedback(x,E),l?.onSubmit?.(x,E)},onDismiss:l?.onDismiss,...l});Ce.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return j.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return j.submitNPSFeedback(l,g)},destroy(){Al(),$o!=null&&(clearInterval($o),$o=null),Ge.forEach(l=>l()),We.remove(),Ze?.remove(),_t?.destroy(),qt?.remove(),Oo&&S.removeEventListener("click",Oo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:Ht,getMessages:Ht.getMessages,getStatus:Ht.getStatus,getMetadata:Ht.getPersistentMetadata,updateMetadata:Ht.updatePersistentMetadata,clearHistory:()=>Ht.clearChat(),setVoiceActive:b=>b?Ht.startVoiceRecognition():Ht.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ge.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=_=>{let J=_.detail;(!J?.instanceId||J.instanceId===l)&&Ht.focusInput()};if(window.addEventListener("persona:focusInput",g),Ge.push(()=>{window.removeEventListener("persona:focusInput",g)}),Z){let _=se=>{let de=se.detail;(!de?.instanceId||de.instanceId===l)&&Ht.showEventStream()},J=se=>{let de=se.detail;(!de?.instanceId||de.instanceId===l)&&Ht.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",J),Ge.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",J)})}let b=_=>{let J=_.detail;(!J?.instanceId||J.instanceId===l)&&Ht.showArtifacts()},x=_=>{let J=_.detail;(!J?.instanceId||J.instanceId===l)&&Ht.hideArtifacts()},E=_=>{let J=_.detail;J?.instanceId&&J.instanceId!==l||J?.artifact&&Ht.upsertArtifact(J.artifact)},R=_=>{let J=_.detail;J?.instanceId&&J.instanceId!==l||typeof J?.id=="string"&&Ht.selectArtifact(J.id)},X=_=>{let J=_.detail;(!J?.instanceId||J.instanceId===l)&&Ht.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",X),Ge.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",X)})}let fn=xv(o.persistState);if(fn&&O()){let l=Cv(fn.storage),g=`${fn.keyPrefix}widget-open`,b=`${fn.keyPrefix}widget-voice`,x=`${fn.keyPrefix}widget-voice-mode`;if(l){let E=fn.persist?.openState&&l.getItem(g)==="true",R=fn.persist?.voiceState&&l.getItem(b)==="true",X=fn.persist?.voiceState&&l.getItem(x)==="true";if(E&&setTimeout(()=>{Ht.open(),setTimeout(()=>{if(R||X)Ht.startVoiceRecognition();else if(fn.persist?.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),fn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(g,"true")}),i.on("widget:closed",()=>{l.setItem(g,"false")})),fn.persist?.voiceState&&(i.on("voice:state",_=>{l.setItem(b,_.active?"true":"false")}),i.on("user:message",_=>{l.setItem(x,_.viaVoice?"true":"false")})),fn.clearOnChatClear){let _=()=>{l.removeItem(g),l.removeItem(b),l.removeItem(x)},J=()=>_();window.addEventListener("persona:clear-chat",J),Ge.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(y&&O()&&setTimeout(()=>{Ht.open()},0),hr(),!Qg){let l=Sr(()=>{j&&(cl++,No.clear(),is(Ce,j.getMessages(),Oe))});Ge.push(l)}return Ht};var ng=(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},Sv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Tv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Ev=(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.")},og=(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"},$c=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=""},rg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",$c(e)},Nc=e=>{e.style.transition=""},Fc=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"},Vi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Mv=(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))},kv=(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)},Lv=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,ri),canvasBackground:o(n?.canvasBackground,si)}},sg=(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},Pv=(e,t,n,o,r,s,a,i)=>{let p=en(s),d=p.reveal==="push",c=i!=null,u=i?.inset??"",y=i?.canvasBackground??"";Mv(e,t,n,o,d),kv(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.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=f!=null?f.innerWidth<=C:!1;if(h&&M&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Fc(t),Nc(o),rg(o),_c(n),Vi(r,o),sg(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"),rg(o),Sv(o,p.maxHeight),sg(o,c&&a,u,y),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Fc(t),Nc(o),_c(n),Vi(r,o);let I=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":A;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=I,o.style.transform=W,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",Nc(o),$c(o),Vi(r,o);let I=ng(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),W=p.animate?"margin-left 180ms ease":"none",$=p.side==="right"?a?-I:0:a?0:-I;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=`${A+I}px`,t.style.transition=W,t.style.marginLeft=`${$}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}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="",Fc(t),$c(o),_c(n),Vi(r,o);let I=p.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=a?p.width:"0px",W=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",$=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",Tv(o,p.maxHeight),o.style.overflow=I||$?"hidden":"visible",o.style.transition=W,I){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let N=c?`calc(${ng(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=N,r.style.minWidth=N,r.style.maxWidth=N,r.style.boxSizing="border-box"}}},Rv=(e,t)=>{let n=e.ownerDocument.createElement("div");return og(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){og(n,o)},destroy(){n.remove()}}},Iv=(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 y=null,f=()=>{y?.disconnect(),y=null},h=null,C=()=>{h=t?.launcher?.detachedPanel===!0?Lv(t):null};C();let M=()=>{Pv(a,i,p,d,c,t,u,h)},P=null,I=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=Dr(()=>{C(),M()}))},A=()=>{f(),en(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{M()}),y.observe(a)))},W=!1,$=()=>{M(),A(),u&&!W&&a.dataset.personaDockMobileFullscreen!=="true"&&(W=!0,Ev(a,en(t)))},N=a.ownerDocument.defaultView,w=()=>{$()};return N?.addEventListener("resize",w),en(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),$(),I(),{mode:"docked",host:c,shell:a,syncWidgetState(q){let V=q.launcherEnabled?q.open:!0;u!==V&&(u=V,$())},updateConfig(q){t=q,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),$(),I()},destroy(){N?.removeEventListener("resize",w),P?.(),P=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},oa=(e,t)=>It(t)?Iv(e,t):Rv(e,t);var Wv=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},ag=(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)},jc=e=>{let t=Wv(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=oa(t,r),a,i=[],p=(M,P)=>{let A=!(P?.launcher?.enabled??!0)||It(P),W=o.createElement("div");if(W.setAttribute("data-persona-root","true"),A&&(W.style.height="100%",W.style.display="flex",W.style.flexDirection="column",W.style.flex="1",W.style.minHeight="0"),n){let $=M.attachShadow({mode:"open"});$.appendChild(W),ag($,o)}else M.appendChild(W),ag(M,o);return t.id&&W.setAttribute("data-persona-instance",t.id),W},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(M=>M()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let M=p(s.host,r);a=qi(M,r,{debugTools:e.debugTools}),c()},y=()=>{i.forEach(M=>M()),i=[],a.destroy()};u(),e.onChatReady?.();let f=M=>{y(),s.destroy(),s=oa(t,M),r=M,u()},h={update(M){let P=Oi(r??{},M),I=It(r),A=It(P),W=Lo(r),$=Lo(P);if(I!==A||W!==$){f(P);return}r=P,s.updateConfig(r),a.update(M),d()},destroy(){y(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(h,{get(M,P,I){if(P==="host")return s.host;if(P in M)return Reflect.get(M,P,I);let A=a[P];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function Hv(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 Bv(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:Hv(o,n)?2:3}function ig(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Ki(e,t){let n=t.trim();if(!n)return[...e].sort(ig);let o=[];for(let r of e){let s=Bv(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:ig(r.item,s.item)),o.map(r=>r.item)}function Dv(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 lg(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Ki(e.items,t),resolve:e.resolve}}function cg(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=>Ki(t,Dv(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 gg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ov=new Set(["button","a","input","select","textarea","details","summary"]),Nv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Uc=/\b(product|card|item|listing|result)\b/i,qc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Fv=3e3,_v=100;function mg(e){let t=typeof e.className=="string"?e.className:"";if(Uc.test(t)||e.id&&Uc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Uc.test(o.value))return!0}return!1}function hg(e){return qc.test((e.textContent??"").trim())}function yg(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 $v(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function dg(e){let t=e.match(qc);return t?t[0]:null}function pg(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 jv(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 Uv="commerce-card",zv="result-card";function ug(e){return!mg(e)||!hg(e)||!yg(e)&&!$v(e)?0:5200}function fg(e){return!mg(e)||hg(e)||!yg(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Vc=[{id:Uv,scoreElement(e){return ug(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||qc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(ug(e)===0)return null;let{title:n,href:o}=pg(e),r=dg((e.textContent??"").trim())??dg(t.text)??"",s=jv(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 fg(e)},formatSummary(e,t){if(fg(e)===0)return null;let{title:n,href:o}=pg(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
+ `)}}];function qv(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Vv(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??Vc;return i==="simple"&&e.rules&&e.rules.length>0?(qv(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function zc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Kv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Gv(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"||Ov.has(t)||n&&Nv.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function bg(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 Jv(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 Kc(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${zc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of Kv){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${zc(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=>zc(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 Xv(e){return e==="static"?_v:Fv}function vg(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Kc(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:Gv(e),attributes:Jv(e)}}function Qv(e,t,n,o){let r=Xv(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 Yv(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 Zv(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(gg.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!bg(d)){i=a.nextNode();continue}let u=vg(d,e.maxTextLength),y=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(M=>M==="role");if(!y&&!f){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:C}=Qv(d,u,e.rules,n);r.push({el:d,domIndex:s,enriched:u,score:h,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y: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;Yv(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let y=d.formattingRule.formatSummary(d.el,d.enriched,n);y&&(c=y)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function ex(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(gg.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!bg(p)){s=r.nextNode();continue}let c=vg(p,e.maxTextLength),u=c.text.length>0,y=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!y){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 xg(e={}){let t=Vv(e),n=t.root??document.body;return n?t.mode==="simple"?ex(t,n):Zv(t,n):[]}var Gi=100;function Cg(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
+ ${s.map(a=>`- ${a.split(`
146
146
  `).join(`
147
147
  `)}`).join(`
148
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let r of e)n==="structured"&&r.formattedSummary||s[r.interactivity].push(r);if(s.clickable.length>0){let r=s.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,Ki)}" (clickable)`);o.push(`Interactive elements:
149
- ${r.join(`
150
- `)}`)}if(s.navigable.length>0){let r=s.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,Ki)}" (navigable)`);o.push(`Navigation links:
151
- ${r.join(`
152
- `)}`)}if(s.input.length>0){let r=s.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,Ki)}" (input)`);o.push(`Form inputs:
153
- ${r.join(`
154
- `)}`)}if(s.static.length>0){let r=s.static.map(a=>`- ${a.selector}: "${a.text.substring(0,Ki)}"`);o.push(`Content:
155
- ${r.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,Gi)}" (clickable)`);o.push(`Interactive elements:
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,Gi)}" (navigable)`);o.push(`Navigation links:
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,Gi)}" (input)`);o.push(`Form inputs:
153
+ ${s.join(`
154
+ `)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,Gi)}"`);o.push(`Content:
155
+ ${s.join(`
156
156
  `)}`)}return o.join(`
157
157
 
158
- `)}function vg(){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 xg(){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 Cg(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:Bn(e.colors.primary,.95),100:Bn(e.colors.primary,.9),200:Bn(e.colors.primary,.8),300:Bn(e.colors.primary,.7),400:Bn(e.colors.primary,.6),500:e.colors.primary,600:Bn(e.colors.primary,.8),700:Bn(e.colors.primary,.7),800:Bn(e.colors.primary,.6),900:Bn(e.colors.primary,.5),950:Bn(e.colors.primary,.45)}}),{...t,palette:n}}}}function wg(){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 Ag(){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 Bn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),r=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Sg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Qv={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"}}},Tg={components:{panel:{borderRadius:"0",shadow:"none"}}},Kc={id:"shop",label:"Shopping Assistant",config:{theme:Qv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:cn},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?"]}},Gc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Tg}},Jc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Tg}},Xc={shop:Kc,minimal:Gc,fullscreen:Jc};function Eg(e){return Xc[e]}var Mg=$c;function Qn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Yv(e){if(e)return{getHeaders:Qn(e.getHeaders),onFeedback:Qn(e.onFeedback),onCopy:Qn(e.onCopy),requestMiddleware:Qn(e.requestMiddleware),actionHandlers:Qn(e.actionHandlers),actionParsers:Qn(e.actionParsers),postprocessMessage:Qn(e.postprocessMessage),contextProviders:Qn(e.contextProviders),streamParser:Qn(e.streamParser)}}var kg=`({ text, message }: any) => {
158
+ `)}function wg(){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 Ag(){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 Sg(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:Bn(e.colors.primary,.95),100:Bn(e.colors.primary,.9),200:Bn(e.colors.primary,.8),300:Bn(e.colors.primary,.7),400:Bn(e.colors.primary,.6),500:e.colors.primary,600:Bn(e.colors.primary,.8),700:Bn(e.colors.primary,.7),800:Bn(e.colors.primary,.6),900:Bn(e.colors.primary,.5),950:Bn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Tg(){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 Eg(){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 Bn(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 Mg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var tx={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"}}},kg={components:{panel:{borderRadius:"0",shadow:"none"}}},Gc={id:"shop",label:"Shopping Assistant",config:{theme:tx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:ln},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?"]}},Jc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:kg}},Xc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:kg}},Qc={shop:Gc,minimal:Jc,fullscreen:Xc};function Lg(e){return Qc[e]}var Pg=jc;function Qn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function nx(e){if(e)return{getHeaders:Qn(e.getHeaders),onFeedback:Qn(e.onFeedback),onCopy:Qn(e.onCopy),requestMiddleware:Qn(e.requestMiddleware),actionHandlers:Qn(e.actionHandlers),actionParsers:Qn(e.actionParsers),postprocessMessage:Qn(e.postprocessMessage),contextProviders:Qn(e.contextProviders),streamParser:Qn(e.streamParser)}}var Rg=`({ 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 @@ ${r.join(`
168
168
  if (parsed.action) return { type: parsed.action, payload: parsed };
169
169
  } catch (e) { return null; }
170
170
  return null;
171
- }`,Lg=`function(ctx) {
171
+ }`,Ig=`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 @@ ${r.join(`
181
181
  if (parsed.action) return { type: parsed.action, payload: parsed };
182
182
  } catch (e) { return null; }
183
183
  return null;
184
- }`,Pg=`(action: any, context: any) => {
184
+ }`,Wg=`(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 @@ ${r.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
- }`,Rg=`function(action, context) {
201
+ }`,Hg=`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 @@ ${r.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
- }`,Zv=`(parsed: any) => {
218
+ }`,ox=`(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
- }`,ex=`function(parsed) {
224
+ }`,rx=`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 tx(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 Gi(e){return e.parserType??tx(e.streamParser)??"plain"}function Ji(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,s])=>{typeof s=="string"&&n.push(`${t} ${o}: "${s}",`)}),n.push(`${t}},`)),n}function Xi(e,t,n){let o=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),r=n?.onFeedback||n?.onCopy;return(s||r)&&(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 Qi(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(o||s)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([r,a])=>{typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Yi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(r=>r!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(r=>r!=="renderUserMessage"&&r!=="renderAssistantMessage");(o||s)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([r,a])=>{r!=="render"&&(typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([r,a])=>{r==="renderUserMessage"||r==="renderAssistantMessage"||(r==="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} },`)):r==="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} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Qc(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 Ig(e,t,n){Object.entries(t).forEach(([o,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${o}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${o}: {`),Ig(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(s)},`)}})}function Po(e,t,n,o){n&&(e.push(`${o}${t}: {`),Ig(e,n,`${o} `),e.push(`${o}},`))}function oa(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Wg(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let s=n?{...n,hooks:Yv(n.hooks)}:void 0;return t==="esm"?nx(o,s):t==="script-installer"?sx(o,s):t==="script-advanced"?ix(o,s):t==="react-component"?ox(o,s):t==="react-advanced"?rx(o,s):ax(o,s)}function nx(e,t){let n=t?.hooks,o=Gi(e),s=o!=="plain",r=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${oa(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(r,"theme",e.theme," "),e.launcher&&Po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ji(e," ")),r.push(...Xi(e," ",n)),r.push(...Qi(e," ")),r.push(...Yi(e," ")),r.push(...Qc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push("});"),r.join(`
231
- `)}function ox(e,t){let n=t?.hooks,o=Gi(e),s=o!=="plain",r=["// 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: '${oa(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(r,"theme",e.theme," "),e.launcher&&Po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ji(e," ")),r.push(...Xi(e," ",n)),r.push(...Qi(e," ")),r.push(...Yi(e," ")),r.push(...Qc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage in your app:"),r.push("// import { ChatWidget } from './components/ChatWidget';"),r.push("//"),r.push("// export default function App() {"),r.push("// return ("),r.push("// <div>"),r.push("// {/* Your app content */}"),r.push("// <ChatWidget />"),r.push("// </div>"),r.push("// );"),r.push("// }"),r.join(`
232
- `)}function rx(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: '${oa(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&&Po(o,"theme",e.theme," "),e.launcher&&Po(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,r])=>{o.push(` ${s}: "${r}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"?o.push(` ${s}: ${r},`):typeof r=="number"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,r])=>{o.push(` ${s}: ${r},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),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(...Ji(e," ")),o.push(...Xi(e," ",n)),o.push(...Qi(e," ")),o.push(...Yi(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(${Zv}),`)),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(` ${kg}`),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(` ${kg}`),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(` ${Pg}`),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(` ${Pg}`),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 Hg(e){let t=Gi(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 s={};Object.entries(e.toolCall).forEach(([r,a])=>{typeof a=="string"&&(s[r]=a)}),Object.keys(s).length>0&&(o.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([r,a])=>{r!=="onFeedback"&&r!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[r]=a)}),Object.keys(s).length>0&&(o.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(o.markdown=s)}if(e.layout){let s={};if(e.layout.header){let r={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.header=r)}if(e.layout.messages){let r={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)r.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&&(r.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.messages=r)}Object.keys(s).length>0&&(o.layout=s)}return o}function sx(e,t){let n=Hg(e),s=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,r=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hn}/dist/install.global.js" data-config='${r}'></script>`}function ax(e,t){let n=t?.hooks,o=Gi(e),s=o!=="plain",r=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${hn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${oa(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(r,"theme",e.theme," "),e.launcher&&Po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ji(e," ")),r.push(...Xi(e," ",n)),r.push(...Qi(e," ")),r.push(...Yi(e," ")),r.push(...Qc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push("</script>"),r.join(`
234
- `)}function ix(e,t){let n=t?.hooks,o=Hg(e),r=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
230
+ }`;function sx(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 Ji(e){return e.parserType??sx(e.streamParser)??"plain"}function Xi(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 Qi(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 Yi(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 Zi(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 Yc(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 Bg(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}: {`),Bg(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Po(e,t,n,o){n&&(e.push(`${o}${t}: {`),Bg(e,n,`${o} `),e.push(`${o}},`))}function ra(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Dg(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:nx(n.hooks)}:void 0;return t==="esm"?ax(o,r):t==="script-installer"?cx(o,r):t==="script-advanced"?px(o,r):t==="react-component"?ix(o,r):t==="react-advanced"?lx(o,r):dx(o,r)}function ax(e,t){let n=t?.hooks,o=Ji(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ra(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&&Po(s,"theme",e.theme," "),e.launcher&&Po(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(...Xi(e," ")),s.push(...Qi(e," ",n)),s.push(...Yi(e," ")),s.push(...Zi(e," ")),s.push(...Yc(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 ix(e,t){let n=t?.hooks,o=Ji(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: '${ra(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&&Po(s,"theme",e.theme," "),e.launcher&&Po(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(...Xi(e," ")),s.push(...Qi(e," ",n)),s.push(...Yi(e," ")),s.push(...Zi(e," ")),s.push(...Yc(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 lx(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: '${ra(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&&Po(o,"theme",e.theme," "),e.launcher&&Po(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(...Xi(e," ")),o.push(...Qi(e," ",n)),o.push(...Yi(e," ")),o.push(...Zi(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(${ox}),`)),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(` ${Rg}`),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(` ${Rg}`),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(` ${Wg}`),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(` ${Wg}`),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 Og(e){let t=Ji(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 cx(e,t){let n=Og(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@${mn}/dist/install.global.js" data-config='${s}'></script>`}function dx(e,t){let n=t?.hooks,o=Ji(e),r=o!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${mn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${mn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ra(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&&Po(s,"theme",e.theme," "),e.launcher&&Po(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(...Xi(e," ")),s.push(...Qi(e," ",n)),s.push(...Yi(e," ")),s.push(...Zi(e," ")),s.push(...Yc(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 px(e,t){let n=t?.hooks,o=Og(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@${hn}/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&&(r.push(` widgetConfig.getHeaders = ${n.getHeaders};`),r.push("")),n?.contextProviders&&(r.push(` widgetConfig.contextProviders = ${n.contextProviders};`),r.push("")),n?.streamParser?r.push(` widgetConfig.streamParser = ${n.streamParser};`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(" widgetConfig.streamParser = function() {"),r.push(` return agentWidget.createFlexibleJsonStreamParser(${ex});`),r.push(" };")),r.push(""),n?.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` var customParsers = ${n.actionParsers};`),r.push(" widgetConfig.actionParsers = customParsers.concat(["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${Lg}`),r.push(" ]);")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" widgetConfig.actionParsers = ["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${Lg}`),r.push(" ];")),r.push(""),n?.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` var customHandlers = ${n.actionHandlers};`),r.push(" widgetConfig.actionHandlers = customHandlers.concat(["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Rg}`),r.push(" ]);")):(r.push(" // Action handlers for navigation and other actions"),r.push(" widgetConfig.actionHandlers = ["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Rg}`),r.push(" ];")),r.push(""),n?.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(` var customResult = (${n.requestMiddleware})(ctx);`),r.push(" var merged = customResult || ctx.payload;"),r.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),r.push(" };")):(r.push(" // Send DOM context with each request"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),r.push(" };")),r.push(""),n?.postprocessMessage?r.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(r.push(" // Markdown postprocessor"),r.push(" widgetConfig.postprocessMessage = function(ctx) {"),r.push(" return agentWidget.markdownPostprocessor(ctx.text);"),r.push(" };")),r.push(""),(n?.onFeedback||n?.onCopy)&&(r.push(" // Message action callbacks"),r.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&r.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&r.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),r.push("")),r.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: '${oa(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>"),r.join(`
237
- `)}var Bg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Dg=.1,Og=.15,Ng=1.5,Yc=24,Fg=40,lx=`
236
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${mn}/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(${rx});`),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(` ${Ig}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ig}`),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(` ${Hg}`),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(` ${Hg}`),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: '${ra(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 Ng={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Fg=.1,_g=.15,$g=1.5,Zc=24,jg=40,ux=`
238
238
  /* \u2500\u2500 Root \u2500\u2500 */
239
239
  .persona-dc-root {
240
240
  display: flex;
@@ -385,7 +385,7 @@ ${r.join(`
385
385
  .persona-dc-stage {
386
386
  height: 550px;
387
387
  min-height: 400px;
388
- padding: ${Yc}px;
388
+ padding: ${Zc}px;
389
389
  overflow: auto;
390
390
  background: #f0f1f3;
391
391
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -475,5 +475,5 @@ ${r.join(`
475
475
  min-height: 300px;
476
476
  }
477
477
  }
478
- `;function cx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=lx,document.head.appendChild(e)}function dx(e,t){let n=e.clientWidth-Yc*2-Fg,o=e.clientHeight-Yc*2-Fg;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function px(e,t,n,o,s){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=s==="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 _g(e,t){let{items:n,initialIndex:o=0,initialDevice:s="desktop",initialColorScheme:r="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");cx();let c=Math.max(0,Math.min(o,n.length-1)),u=s,y=r,f=null,h=1,C=!1,M=m("div","persona-dc-root"),P=m("div","persona-dc-toolbar"),I=m("div","persona-dc-toolbar-lead"),A=m("div","persona-dc-toolbar-trail"),W=mt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ze(-1)}),$=m("div");$.style.position="relative";let N=m("button","persona-dc-title-btn");N.type="button",N.setAttribute("aria-expanded","false"),N.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),z=m("span","persona-dc-title-chevron"),V=oe("chevron-down",12,"currentColor",2);V&&z.appendChild(V),N.append(w,z);let Y=m("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let O=!1;function U(){Y.innerHTML="";for(let le=0;le<n.length;le++){let Ie=n[le],Ct=m("button","persona-dc-dropdown-item");Ct.type="button",Ct.setAttribute("role","option"),Ct.setAttribute("aria-current",le===c?"true":"false");let bt=m("span");if(bt.textContent=Ie.title,Ct.appendChild(bt),Ie.description){let st=m("span","persona-dc-dropdown-desc");st.textContent=Ie.description,Ct.appendChild(st)}Ct.addEventListener("click",()=>{be(),Fe(le)}),Y.appendChild(Ct)}}function me(){O=!O,Y.style.display=O?"":"none",N.setAttribute("aria-expanded",O?"true":"false"),O&&U()}function be(){O&&(O=!1,Y.style.display="none",N.setAttribute("aria-expanded","false"))}N.addEventListener("click",le=>{le.stopPropagation(),me()});let Me=()=>be();document.addEventListener("click",Me),$.append(N,Y);let Oe=mt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ze(1)}),ae=m("span","persona-dc-counter");I.append(W,$,Oe,ae);let ve=null;i&&(ve=Jn({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:le=>{u=le,he.dataset.device=u,f=null,Ae()}}),A.appendChild(ve.element));let Z=null;if(a){let le=m("div","persona-dc-zoom-controls"),Ie=mt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(Og,(f??h)-Dg),Ae()}});Z=m("span","persona-dc-zoom-level"),Z.title="Reset to 100%",Z.style.cursor="pointer",Z.addEventListener("click",()=>{f=1,Ae()});let Ct=mt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(Ng,(f??h)+Dg),Ae()}}),bt=mt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,Ae()}});le.append(Ie,Z,Ct,bt),A.appendChild(le)}if(p){let le=m("div","persona-dc-separator");A.appendChild(le);let Ie=Jn({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Ct=>{y=Ct,he.dataset.colorScheme=y,Re()}});A.appendChild(Ie.element)}let de=m("div","persona-dc-separator");A.appendChild(de);let ee=mt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});A.appendChild(ee),P.append(I,A);let Ce=m("div","persona-dc-stage"),he=m("div","persona-dc-iframe-wrapper");he.dataset.device=u,he.dataset.colorScheme=y;let fe=m("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[c].title,he.appendChild(fe),Ce.appendChild(he),M.append(P,Ce),e.appendChild(M);function Re(){try{let le=fe.contentDocument?.body;if(!le)return;y==="dark"?le.classList.add("theme-dark"):le.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>Re());function Ne(){let le=n[c];w.textContent=le.title,ae.textContent=`${c+1} / ${n.length}`,fe.title=le.title}function ze(le){let Ie=((c+le)%n.length+n.length)%n.length;Fe(Ie)}function Fe(le){le<0||le>=n.length||(c=le,fe.src=n[c].url,Ne(),d?.(c,n[c]))}function Ae(){if(C)return;let le=Bg[u]??Bg.desktop;h=dx(Ce,le);let Ie=Math.max(Og,Math.min(Ng,f??h));px(he,fe,le,Ie,u),Z&&(Z.textContent=`${Math.round(Ie*100)}%`)}let Pe=new ResizeObserver(()=>Ae());Pe.observe(Ce),Ne(),fe.src=n[c].url,requestAnimationFrame(()=>Ae());function rt(){C||(C=!0,Pe.disconnect(),document.removeEventListener("click",Me),M.remove())}return{element:M,goTo:Fe,next:()=>ze(1),prev:()=>ze(-1),getIndex:()=>c,setDevice(le){u=le,he.dataset.device=le,ve?.setSelected(le),f=null,Ae()},setColorScheme(le){y=le,he.dataset.colorScheme=le},setZoom(le){f=le,Ae()},destroy:rt}}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 fx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=ux,document.head.appendChild(e)}function gx(e,t){let n=e.clientWidth-Zc*2-jg,o=e.clientHeight-Zc*2-jg;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function mx(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 Ug(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");fx();let c=Math.max(0,Math.min(o,n.length-1)),u=r,y=s,f=null,h=1,C=!1,M=m("div","persona-dc-root"),P=m("div","persona-dc-toolbar"),I=m("div","persona-dc-toolbar-lead"),A=m("div","persona-dc-toolbar-trail"),W=gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>je(-1)}),$=m("div");$.style.position="relative";let N=m("button","persona-dc-title-btn");N.type="button",N.setAttribute("aria-expanded","false"),N.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),q=m("span","persona-dc-title-chevron"),V=ne("chevron-down",12,"currentColor",2);V&&q.appendChild(V),N.append(w,q);let Y=m("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let O=!1;function U(){Y.innerHTML="";for(let oe=0;oe<n.length;oe++){let Ie=n[oe],Ct=m("button","persona-dc-dropdown-item");Ct.type="button",Ct.setAttribute("role","option"),Ct.setAttribute("aria-current",oe===c?"true":"false");let yt=m("span");if(yt.textContent=Ie.title,Ct.appendChild(yt),Ie.description){let pt=m("span","persona-dc-dropdown-desc");pt.textContent=Ie.description,Ct.appendChild(pt)}Ct.addEventListener("click",()=>{ve(),Be(oe)}),Y.appendChild(Ct)}}function me(){O=!O,Y.style.display=O?"":"none",N.setAttribute("aria-expanded",O?"true":"false"),O&&U()}function ve(){O&&(O=!1,Y.style.display="none",N.setAttribute("aria-expanded","false"))}N.addEventListener("click",oe=>{oe.stopPropagation(),me()});let Me=()=>ve();document.addEventListener("click",Me),$.append(N,Y);let Oe=gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>je(1)}),ie=m("span","persona-dc-counter");I.append(W,$,Oe,ie);let xe=null;i&&(xe=Jn({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:oe=>{u=oe,he.dataset.device=u,f=null,Ue()}}),A.appendChild(xe.element));let Z=null;if(a){let oe=m("div","persona-dc-zoom-controls"),Ie=gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(_g,(f??h)-Fg),Ue()}});Z=m("span","persona-dc-zoom-level"),Z.title="Reset to 100%",Z.style.cursor="pointer",Z.addEventListener("click",()=>{f=1,Ue()});let Ct=gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min($g,(f??h)+Fg),Ue()}}),yt=gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,Ue()}});oe.append(Ie,Z,Ct,yt),A.appendChild(oe)}if(p){let oe=m("div","persona-dc-separator");A.appendChild(oe);let Ie=Jn({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Ct=>{y=Ct,he.dataset.colorScheme=y,Re()}});A.appendChild(Ie.element)}let ce=m("div","persona-dc-separator");A.appendChild(ce);let ee=gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});A.appendChild(ee),P.append(I,A);let we=m("div","persona-dc-stage"),he=m("div","persona-dc-iframe-wrapper");he.dataset.device=u,he.dataset.colorScheme=y;let ue=m("iframe","persona-dc-iframe");ue.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ue.setAttribute("loading","lazy"),ue.title=n[c].title,he.appendChild(ue),we.appendChild(he),M.append(P,we),e.appendChild(M);function Re(){try{let oe=ue.contentDocument?.body;if(!oe)return;y==="dark"?oe.classList.add("theme-dark"):oe.classList.remove("theme-dark")}catch{}}ue.addEventListener("load",()=>Re());function Ne(){let oe=n[c];w.textContent=oe.title,ie.textContent=`${c+1} / ${n.length}`,ue.title=oe.title}function je(oe){let Ie=((c+oe)%n.length+n.length)%n.length;Be(Ie)}function Be(oe){oe<0||oe>=n.length||(c=oe,ue.src=n[c].url,Ne(),d?.(c,n[c]))}function Ue(){if(C)return;let oe=Ng[u]??Ng.desktop;h=gx(we,oe);let Ie=Math.max(_g,Math.min($g,f??h));mx(he,ue,oe,Ie,u),Z&&(Z.textContent=`${Math.round(Ie*100)}%`)}let Xe=new ResizeObserver(()=>Ue());Xe.observe(we),Ne(),ue.src=n[c].url,requestAnimationFrame(()=>Ue());function ke(){C||(C=!0,Xe.disconnect(),document.removeEventListener("click",Me),M.remove())}return{element:M,goTo:Be,next:()=>je(1),prev:()=>je(-1),getIndex:()=>c,setDevice(oe){u=oe,he.dataset.device=oe,xe?.setSelected(oe),f=null,Ue()},setColorScheme(oe){y=oe,he.dataset.colorScheme=oe},setZoom(oe){f=oe,Ue()},destroy:ke}}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