@runtypelabs/persona 4.6.0 → 4.7.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,22 +1,22 @@
1
- "use strict";var Kh=Object.create;var Xa=Object.defineProperty;var Gh=Object.getOwnPropertyDescriptor;var Jh=Object.getOwnPropertyNames;var Xh=Object.getPrototypeOf,Qh=Object.prototype.hasOwnProperty;var Ms=(e,t)=>()=>(e&&(t=e(e=0)),t);var Qa=(e,t)=>{for(var n in t)Xa(e,n,{get:t[n],enumerable:!0})},xm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jh(t))!Qh.call(e,o)&&o!==n&&Xa(e,o,{get:()=>t[o],enumerable:!(r=Gh(t,o))||r.enumerable});return e};var Cl=(e,t,n)=>(n=e!=null?Kh(Xh(e)):{},xm(t||!e||!e.__esModule?Xa(n,"default",{value:e,enumerable:!0}):n,e)),Yh=e=>xm(Xa({},"__esModule",{value:!0}),e);var Cm={};Qa(Cm,{DOMPurify:()=>wm.default,Marked:()=>vm.Marked});var vm,wm,Am=Ms(()=>{"use strict";vm=require("marked"),wm=Cl(require("dompurify"),1)});var Ds,Ol=Ms(()=>{"use strict";Ds=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.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)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function eb(e){return e.replace(/\/+$/,"")}async function tb(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var yi,Ag=Ms(()=>{"use strict";Ol();yi=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ds(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${eb(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await tb(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var bi,Sg=Ms(()=>{"use strict";bi=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Tg={};Qa(Tg,{FallbackSpeechEngine:()=>bi,RuntypeSpeechEngine:()=>yi});var Eg=Ms(()=>{"use strict";Ag();Sg()});var kg={};Qa(kg,{createReconnectController:()=>rb});function rb(e){let t=0,n=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),n){let b=n;n=null,b()}},a=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},i=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",i),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},p=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",i),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},u=b=>new Promise(v=>{n=v,r=setTimeout(()=>{r=null,n=null,v()},b)}),f=()=>{var E;let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let P of e.getMessages())P.streaming&&(P.streaming=!1,v=!0);let T=e.buildErrorContent("Connection lost and the response could not be resumed.");T?e.appendMessage({id:`reconnect-failed-${(E=b==null?void 0:b.executionId)!=null?E:e.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{var E,P,I,M,L,C;let b=(P=(E=e.config.reconnect)==null?void 0:E.backoffMs)!=null?P:nb,v=(M=(I=e.config.reconnect)==null?void 0:I.maxAttempts)!=null?M:b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let R=e.getResumable(),U=R.lastEventId,j=new AbortController;e.setAbortController(j),e.emitReconnect({phase:"resuming",handle:R,attempt:t});let W=null;try{let O=await T({executionId:R.executionId,after:R.lastEventId,signal:j.signal});O&&O.ok&&O.body&&(W=O.body)}catch{W=null}if(j.signal.aborted)return;if(W){let O=(L=e.getMessages().find(ee=>ee.id===R.assistantMessageId))==null?void 0:L.content,F=typeof O=="string"?O:"";try{await e.resumeConnect(W,R.assistantMessageId,F)}catch{}if(j.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:R});return}e.getResumable().lastEventId!==U&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await u((C=b[Math.min(t-1,b.length-1)])!=null?C:1e3),j.signal.aborted))return}e.getResumable()&&f()};return{begin(){t=0,c(),g()},teardown(){r&&(clearTimeout(r),r=null),n=null,t=0,p()},wake:s}}var nb,Lg=Ms(()=>{"use strict";nb=[1e3,2e3,4e3,8e3,8e3]});var Rv={};Qa(Rv,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Bl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Hl,ASK_USER_QUESTION_TOOL_NAME:()=>fa,AgentWidgetClient:()=>ss,AgentWidgetSession:()=>Os,AttachmentManager:()=>ls,BrowserSpeechEngine:()=>Io,DEFAULT_COMPONENTS:()=>ql,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>vi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>zn,DEFAULT_PALETTE:()=>jl,DEFAULT_SEMANTIC:()=>Ul,DEFAULT_WIDGET_CONFIG:()=>Bt,PRESETS:()=>Ic,PRESET_FULLSCREEN:()=>Pc,PRESET_MINIMAL:()=>Lc,PRESET_SHOP:()=>kc,ReadAloudController:()=>is,SUGGEST_REPLIES_CLIENT_TOOL:()=>ri,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Il,SUGGEST_REPLIES_TOOL_NAME:()=>br,THEME_ZONES:()=>Bg,VERSION:()=>or,WEBMCP_TOOL_PREFIX:()=>yr,WebMcpBridge:()=>Is,accessibilityPlugin:()=>rh,animationsPlugin:()=>oh,applyThemeVariables:()=>Ro,attachHeaderToContainer:()=>cs,brandPlugin:()=>sh,buildComposer:()=>qs,buildDefaultHeader:()=>Ql,buildHeader:()=>Zr,buildHeaderWithLayout:()=>Us,buildMinimalHeader:()=>Yl,builtInClientToolsForDispatch:()=>ba,collectEnrichedPageContext:()=>th,componentRegistry:()=>eo,createActionManager:()=>$a,createAgentExperience:()=>rl,createAskUserQuestionBubble:()=>ng,createBestAvailableVoiceProvider:()=>hi,createBubbleWithLayout:()=>lf,createCSATFeedback:()=>el,createComboButton:()=>Di,createComponentMiddleware:()=>Df,createComponentStreamParser:()=>Xi,createDefaultSanitizer:()=>Sl,createDemoCarousel:()=>Sh,createDirectivePostprocessor:()=>Rm,createDropdownMenu:()=>No,createFlexibleJsonStreamParser:()=>ag,createIconButton:()=>Gt,createImagePart:()=>gg,createJsonStreamParser:()=>pi,createLabelButton:()=>Ha,createLocalStorageAdapter:()=>Ji,createMarkdownProcessor:()=>pa,createMarkdownProcessorFromConfig:()=>rs,createMessageActions:()=>sc,createNPSFeedback:()=>tl,createPlainTextParser:()=>ci,createPlugin:()=>lh,createRegexJsonParser:()=>di,createStandardBubble:()=>zs,createTextPart:()=>Ca,createTheme:()=>_s,createThemeObserver:()=>Si,createToggleGroup:()=>Ba,createTypingIndicator:()=>ds,createVoiceProvider:()=>Po,createWidgetHostLayout:()=>ja,createXmlParser:()=>ui,default:()=>ph,defaultActionHandlers:()=>gs,defaultJsonActionParser:()=>_a,defaultParseRules:()=>Ec,detectColorScheme:()=>Ma,directivePostprocessor:()=>Wm,ensureAskUserQuestionSheet:()=>Hs,escapeHtml:()=>Br,extractComponentDirectiveFromMessage:()=>Zi,fileToImagePart:()=>fg,formatEnrichedContext:()=>nh,generateAssistantMessageId:()=>Lo,generateCodeSnippet:()=>yh,generateMessageId:()=>cg,generateStableSelector:()=>Mc,generateUserMessageId:()=>Bs,getActiveTheme:()=>$s,getColorScheme:()=>Vl,getDisplayText:()=>pg,getHeaderLayout:()=>Zl,getImageParts:()=>mg,getPreset:()=>dh,hasComponentDirective:()=>Yi,hasImages:()=>ug,headerLayouts:()=>Ni,highContrastPlugin:()=>ih,initAgentWidget:()=>Cc,isAskUserQuestionMessage:()=>Jr,isComponentDirectiveType:()=>Bf,isDockedMountMode:()=>on,isSuggestRepliesMessage:()=>ya,isVoiceSupported:()=>Sa,isWebMcpToolName:()=>Ao,latestAgentSuggestions:()=>oi,listRegisteredStreamAnimations:()=>Yg,markdownPostprocessor:()=>Al,mergeWithDefaults:()=>wi,normalizeContent:()=>dg,parseAskUserQuestionPayload:()=>Xr,parseSuggestRepliesPayload:()=>Wl,pickBestVoice:()=>Ns,pluginRegistry:()=>Fa,reducedMotionPlugin:()=>ah,registerStreamAnimationPlugin:()=>Xg,removeAskUserQuestionSheet:()=>Eo,renderComponentDirective:()=>Qi,renderLoadingIndicatorWithFallback:()=>oc,renderLucideIcon:()=>he,resolveDockConfig:()=>Vn,resolveSanitizer:()=>Ps,resolveTokens:()=>Ci,stripWebMcpPrefix:()=>Za,themeToCssVariables:()=>Ai,unregisterStreamAnimationPlugin:()=>Qg,validateImageFile:()=>hg,validateTheme:()=>zl});module.exports=Yh(Rv);var Mm=require("marked"),km=Cl(require("dompurify"),1);var Sm=null,Ls=null,ks=null;var Tm=e=>{Ls=e},Em=()=>Ls?Promise.resolve(Ls):ks||(Sm?(ks=Sm().then(e=>(Ls=e,e)),ks):(ks=Promise.resolve().then(()=>(Am(),Cm)).then(e=>(Ls=e,e)),ks)),ns=()=>Ls;Tm({Marked:Mm.Marked,DOMPurify:km.default});var Zh=e=>{if(e)return e},pa=e=>{let t=null;return n=>{var o,s;let r=ns();if(!r)return Br(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Zh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},rs=e=>e?pa({markedOptions:e.options,renderer:e.renderer}):pa(),ey=pa(),Al=e=>ey(e),Br=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Pm=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Lm=e=>`%%FORM_PLACEHOLDER_${e}%%`,Im=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Lm(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Lm(t.length);return t.push({token:s,type:o}),s}),n},Rm=e=>{let t=rs(e);return n=>{let r=[],o=Im(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Pm(i)}"></div>`;s=s.replace(d,p)}),s}},Wm=e=>{let t=[],n=Im(e,t),r=Al(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Pm(s)}"></div>`;r=r.replace(a,d)}),r};var ty={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"]},ny=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Sl=()=>{let e=null;return t=>{let n=ns();if(!n)return Br(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!ny.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,ty)}},Ps=e=>e===!1?null:typeof e=="function"?e:Sl();var Hm=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Bm=e=>e.includes("|"),Dm=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())},ry=e=>`| ${e.join(" | ")} |`,oy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,sy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Nm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!Bm(o)||Hm.test(o)||!Hm.test(s))continue;let a=Dm(o).length;if(a<1)continue;let i=oy(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let c=t[d];if(c.trim()===""||!Bm(c))break;let p=ry(sy(Dm(c),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
- `):e};var yr="webmcp:",Tl=new Map,Om=e=>{var t;Tl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Tl.set(n.name,r)}},ua=e=>Tl.get(Za(e)),Ya={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Fm=null;function $m(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${ay(t.join(""))}`}function _m(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function ay(e){let t=_m(e,0).toString(36),n=_m(e,2654435761).toString(36);return`${t}.${n}`}var Is=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return Ya.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Om(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=ly(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let b=typeof document!="undefined"&&!!document.modelContext;return hr(b?"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=Za(t),a;try{a=await o.getTools()}catch(b){let v=b instanceof Error?b.message:String(b);return hr(`Failed to read WebMCP registry: ${v}`)}Om(a);let i=a.find(b=>b.name===s);if(!i)return hr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return hr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d=ua(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let b=await o.executeTool(i,uy(n),{signal:p.signal});return cy(b)}catch(b){if(u)return hr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=b instanceof Error?b.message:String(b);return hr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Fm?await Fm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ya.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ya.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:dy;try{return await n(t)}catch(o){return Ya.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(r=>iy(t,r))}},Za=e=>e.startsWith(yr)?e.slice(yr.length):e,Ao=e=>e.startsWith(yr),iy=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},ly=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},cy=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:my(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),dy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=py(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var ly=Object.create;var ti=Object.defineProperty;var cy=Object.getOwnPropertyDescriptor;var dy=Object.getOwnPropertyNames;var py=Object.getPrototypeOf,uy=Object.prototype.hasOwnProperty;var Ps=(e,t)=>()=>(e&&(t=e(e=0)),t);var ni=(e,t)=>{for(var n in t)ti(e,n,{get:t[n],enumerable:!0})},Im=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of dy(t))!uy.call(e,o)&&o!==n&&ti(e,o,{get:()=>t[o],enumerable:!(r=cy(t,o))||r.enumerable});return e};var Pl=(e,t,n)=>(n=e!=null?ly(py(e)):{},Im(t||!e||!e.__esModule?ti(n,"default",{value:e,enumerable:!0}):n,e)),my=e=>Im(ti({},"__esModule",{value:!0}),e);var Hm={};ni(Hm,{DOMPurify:()=>Wm.default,Marked:()=>Rm.Marked});var Rm,Wm,Bm=Ps(()=>{"use strict";Rm=require("marked"),Wm=Pl(require("dompurify"),1)});var _s,Vl=Ps(()=>{"use strict";_s=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.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)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function fb(e){return e.replace(/\/+$/,"")}async function hb(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Ci,Bg=Ps(()=>{"use strict";Vl();Ci=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new _s(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${fb(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await hb(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Ai,Dg=Ps(()=>{"use strict";Ai=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Ng={};ni(Ng,{FallbackSpeechEngine:()=>Ai,RuntypeSpeechEngine:()=>Ci});var Og=Ps(()=>{"use strict";Bg();Dg()});var _g={};ni(_g,{createReconnectController:()=>bb});function bb(e){let t=0,n=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",i),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},p=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",i),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},u=y=>new Promise(v=>{n=v,r=setTimeout(()=>{r=null,n=null,v()},y)}),f=()=>{var E;let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let P of e.getMessages())P.streaming&&(P.streaming=!1,v=!0);let S=e.buildErrorContent("Connection lost and the response could not be resumed.");S?e.appendMessage({id:`reconnect-failed-${(E=y==null?void 0:y.executionId)!=null?E:e.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{var E,P,H,W,I,T;let y=(P=(E=e.config.reconnect)==null?void 0:E.backoffMs)!=null?P:yb,v=(W=(H=e.config.reconnect)==null?void 0:H.maxAttempts)!=null?W:y.length,S=e.config.reconnectStream;if(!S){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let B=e.getResumable(),q=B.lastEventId,U=new AbortController;e.setAbortController(U),e.emitReconnect({phase:"resuming",handle:B,attempt:t});let L=null;try{let F=await S({executionId:B.executionId,after:B.lastEventId,signal:U.signal});F&&F.ok&&F.body&&(L=F.body)}catch{L=null}if(U.signal.aborted)return;if(L){let F=(I=e.getMessages().find(ee=>ee.id===B.assistantMessageId))==null?void 0:I.content,_=typeof F=="string"?F:"";try{await e.resumeConnect(L,B.assistantMessageId,_)}catch{}if(U.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:B});return}e.getResumable().lastEventId!==q&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await u((T=y[Math.min(t-1,y.length-1)])!=null?T:1e3),U.signal.aborted))return}e.getResumable()&&f()};return{begin(){t=0,c(),g()},teardown(){r&&(clearTimeout(r),r=null),n=null,t=0,p()},wake:s}}var yb,$g=Ps(()=>{"use strict";yb=[1e3,2e3,4e3,8e3,8e3]});var Kv={};ni(Kv,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Ul,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>jl,ASK_USER_QUESTION_TOOL_NAME:()=>xa,AgentWidgetClient:()=>is,AgentWidgetSession:()=>js,AttachmentManager:()=>ds,BrowserSpeechEngine:()=>Wo,DEFAULT_COMPONENTS:()=>Yl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ti,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>zn,DEFAULT_PALETTE:()=>Xl,DEFAULT_SEMANTIC:()=>Ql,DEFAULT_WIDGET_CONFIG:()=>Bt,PRESETS:()=>Fc,PRESET_FULLSCREEN:()=>Oc,PRESET_MINIMAL:()=>Nc,PRESET_SHOP:()=>Dc,ReadAloudController:()=>cs,SUGGEST_REPLIES_CLIENT_TOOL:()=>li,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Fl,SUGGEST_REPLIES_TOOL_NAME:()=>yr,THEME_ZONES:()=>Kg,VERSION:()=>or,WEBMCP_TOOL_PREFIX:()=>hr,WebMcpBridge:()=>Hs,accessibilityPlugin:()=>fh,animationsPlugin:()=>hh,applyThemeVariables:()=>Ho,attachHeaderToContainer:()=>ps,brandPlugin:()=>yh,buildComposer:()=>Gs,buildDefaultHeader:()=>sc,buildHeader:()=>no,buildHeaderWithLayout:()=>Ks,buildMinimalHeader:()=>ac,builtInClientToolsForDispatch:()=>Os,collectEnrichedPageContext:()=>mh,componentRegistry:()=>ro,createActionManager:()=>qa,createAgentExperience:()=>il,createAskUserQuestionBubble:()=>gg,createBestAvailableVoiceProvider:()=>wi,createBubbleWithLayout:()=>vf,createCSATFeedback:()=>ol,createComboButton:()=>$i,createComponentMiddleware:()=>Gf,createComponentStreamParser:()=>tl,createDefaultSanitizer:()=>Rl,createDemoCarousel:()=>Dh,createDirectivePostprocessor:()=>qm,createDropdownMenu:()=>Fo,createFlexibleJsonStreamParser:()=>bg,createIconButton:()=>Gt,createImagePart:()=>Eg,createJsonStreamParser:()=>hi,createLabelButton:()=>Na,createLocalStorageAdapter:()=>el,createMarkdownProcessor:()=>fa,createMarkdownProcessorFromConfig:()=>ss,createMessageActions:()=>mc,createNPSFeedback:()=>sl,createPlainTextParser:()=>gi,createPlugin:()=>vh,createRegexJsonParser:()=>fi,createStandardBubble:()=>Js,createTextPart:()=>Ta,createTheme:()=>qs,createThemeObserver:()=>Li,createToggleGroup:()=>Oa,createTypingIndicator:()=>us,createVoiceProvider:()=>Ro,createWidgetHostLayout:()=>Va,createXmlParser:()=>yi,default:()=>Ah,defaultActionHandlers:()=>hs,defaultJsonActionParser:()=>Ua,defaultParseRules:()=>Hc,detectColorScheme:()=>Pa,directivePostprocessor:()=>zm,ensureAskUserQuestionSheet:()=>Ns,escapeHtml:()=>Br,extractComponentDirectiveFromMessage:()=>rl,fileToImagePart:()=>Mg,formatEnrichedContext:()=>gh,generateAssistantMessageId:()=>Io,generateCodeSnippet:()=>Lh,generateMessageId:()=>wg,generateStableSelector:()=>Bc,generateUserMessageId:()=>Fs,getActiveTheme:()=>zs,getColorScheme:()=>ec,getDisplayText:()=>Ag,getHeaderLayout:()=>ic,getImageParts:()=>Tg,getPreset:()=>Ch,hasComponentDirective:()=>za,hasImages:()=>Sg,headerLayouts:()=>ji,highContrastPlugin:()=>xh,initAgentWidget:()=>Pc,isAskUserQuestionMessage:()=>Yr,isComponentDirectiveType:()=>Kf,isDockedMountMode:()=>rn,isSuggestRepliesMessage:()=>wa,isVoiceSupported:()=>Ma,isWebMcpToolName:()=>To,latestAgentSuggestions:()=>ci,listRegisteredStreamAnimations:()=>pf,markdownPostprocessor:()=>Il,mergeWithDefaults:()=>Ei,normalizeContent:()=>Cg,parseAskUserQuestionPayload:()=>Zr,parseSuggestRepliesPayload:()=>$l,pickBestVoice:()=>$s,pluginRegistry:()=>ja,reducedMotionPlugin:()=>bh,registerStreamAnimationPlugin:()=>cf,removeAskUserQuestionSheet:()=>ko,renderComponentDirective:()=>nl,renderLoadingIndicatorWithFallback:()=>uc,renderLucideIcon:()=>he,resolveDockConfig:()=>Vn,resolveSanitizer:()=>Ws,resolveTokens:()=>Mi,stripWebMcpPrefix:()=>oi,themeToCssVariables:()=>ki,unregisterStreamAnimationPlugin:()=>df,validateImageFile:()=>kg,validateTheme:()=>Zl});module.exports=my(Kv);var Fm=require("marked"),_m=Pl(require("dompurify"),1);var Dm=null,Rs=null,Is=null;var Nm=e=>{Rs=e},Om=()=>Rs?Promise.resolve(Rs):Is||(Dm?(Is=Dm().then(e=>(Rs=e,e)),Is):(Is=Promise.resolve().then(()=>(Bm(),Hm)).then(e=>(Rs=e,e)),Is)),os=()=>Rs;Nm({Marked:Fm.Marked,DOMPurify:_m.default});var gy=e=>{if(e)return e},fa=e=>{let t=null;return n=>{var o,s;let r=os();if(!r)return Br(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=gy(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},ss=e=>e?fa({markedOptions:e.options,renderer:e.renderer}):fa(),fy=fa(),Il=e=>fy(e),Br=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),jm=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),$m=e=>`%%FORM_PLACEHOLDER_${e}%%`,Um=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=$m(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=$m(t.length);return t.push({token:s,type:o}),s}),n},qm=e=>{let t=ss(e);return n=>{let r=[],o=Um(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${jm(i)}"></div>`;s=s.replace(d,p)}),s}},zm=e=>{let t=[],n=Um(e,t),r=Il(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${jm(s)}"></div>`;r=r.replace(a,d)}),r};var hy={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"]},yy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Rl=()=>{let e=null;return t=>{let n=os();if(!n)return Br(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!yy.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,hy)}},Ws=e=>e===!1?null:typeof e=="function"?e:Rl();var Vm=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Km=e=>e.includes("|"),Gm=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())},by=e=>`| ${e.join(" | ")} |`,xy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,vy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Jm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!Km(o)||Vm.test(o)||!Vm.test(s))continue;let a=Gm(o).length;if(a<1)continue;let i=xy(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let c=t[d];if(c.trim()===""||!Km(c))break;let p=by(vy(Gm(c),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
+ `):e};var hr="webmcp:",Wl=new Map,Xm=e=>{var t;Wl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Wl.set(n.name,r)}},ha=e=>Wl.get(oi(e)),ri={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Qm=null;function Zm(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${wy(t.join(""))}`}function Ym(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function wy(e){let t=Ym(e,0).toString(36),n=Ym(e,2654435761).toString(36);return`${t}.${n}`}var Hs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return ri.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Xm(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Ay(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return fr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let y=typeof document!="undefined"&&!!document.modelContext;return fr(y?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=oi(t),a;try{a=await o.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return fr(`Failed to read WebMCP registry: ${v}`)}Xm(a);let i=a.find(y=>y.name===s);if(!i)return fr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return fr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return fr("Aborted by cancel()");let d=ha(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return fr("User declined the tool call.");if(r!=null&&r.aborted)return fr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let y=await o.executeTool(i,My(n),{signal:p.signal});return Sy(y)}catch(y){if(u)return fr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return fr("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return fr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Qm?await Qm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ri.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ri.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Ty;try{return await n(t)}catch(o){return ri.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(r=>Cy(t,r))}},oi=e=>e.startsWith(hr)?e.slice(hr.length):e,To=e=>e.startsWith(hr),Cy=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ay=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Sy=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:ky(t)}]}},fr=e=>({isError:!0,content:[{type:"text",text:e}]}),Ty=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ey(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)},py=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},uy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},my=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var gy="agent_",fy="flow_";function jm(e){return e.startsWith(gy)?{kind:"agentId",agentId:e}:e.startsWith(fy)?{kind:"flowId",flowId:e}:null}function Um(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=jm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)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:d(i).payload}}let o=jm(n);if(o)return o;let s=t==null?void 0: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 So=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Dr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Mt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},ma=(...e)=>e.filter(Boolean).join(" ");var fa="ask_user_question",ga=8,Rs="data-persona-ask-sheet-for",hy="Other",yy="Other\u2026",zm="Type your own answer here",Vm="Send",by="Next",xy="Back",vy="Submit all",wy="Skip",Cy=3,El="data-ask-current-index",Ml="data-ask-question-count",Km="data-ask-answers",kl="data-ask-grouped",Gm="data-ask-layout",Ay=e=>e.layout==="pills"?"pills":"rows",Sy=e=>e.getAttribute(Gm)==="pills"?"pills":"rows",qm=!1,Jm=e=>e.replace(/["\\]/g,"\\$&"),Jr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===fa,ei=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,So.parse)(o,So.STR|So.OBJ|So.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ha=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ga&&!qm&&(qm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ga}.`)),t.slice(0,ga)},Ty=e=>{var t;return(t=ha(e)[0])!=null?t:null},Ey=(e,t)=>{var n;return(n=ha(e)[t])!=null?n:null},Xm=(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))},Qm=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},My=(e,t,n,r)=>{let s=y("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",r?"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=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=Qm(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ky=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Ly=(e,t,n,r)=>{var p,u,f;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Cy;g++)s.appendChild(ky(r));return s}if(d.forEach((g,b)=>{s.appendChild(My(g,b,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?hy:yy;if(r==="rows"){let b=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(p=t.freeTextPlaceholder)!=null?p:zm,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(T),b.appendChild(v);let E=Qm(r,a,d.length);E&&b.appendChild(E),s.appendChild(b)}else{let b=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(b)}}return s},Ym=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:zm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Vm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Py=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Vm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Iy=(e,t,n)=>{var c,p,u,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:xy,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:wy,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:vy:(f=n.nextLabel)!=null?f:by,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},os=e=>{let t=e.getAttribute(Km);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zm=(e,t)=>{e.setAttribute(Km,JSON.stringify(t))},rr=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ry=(e,t)=>{e.setAttribute(El,String(Math.max(0,Math.floor(t))))},Ws=e=>{var n;let t=Number((n=e.getAttribute(Ml))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},To=e=>e.getAttribute(kl)==="true",Wy=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Hy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ti=(e,t)=>{let{payload:n}=Xr(t),r=ha(n),o=os(e),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},eg=e=>{let t=os(e),n=rr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},tg=e=>{if(!To(e))return;let t=os(e),n=rr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},Ll=(e,t,n)=>{let r=ei(n),o=Sy(e),{payload:s,complete:a}=Xr(t),i=To(e),d=rr(e),c=Ws(e),p=i?Ey(s,d):Ty(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let P=typeof(p==null?void 0:p.question)=="string"?p.question:"";b.textContent=P,b.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let P=Ly(p,r,a,o);v.replaceWith(P)}if(o!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Ym(r,o))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!T?e.appendChild(Py(r)):(!u||i)&&T&&T.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=Iy(d,c,r);E?E.replaceWith(P):e.appendChild(P)}else E&&E.remove();eg(e),tg(e)},By=(e,t,n)=>{let r=ei(t),o=Ay(r),s=e.toolCall.id,a=ha(n),i=Math.max(1,a.length),d=i>1,c=Wy(e,a),p=d?Hy(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Rs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Ml,String(i)),u.setAttribute(El,String(p)),u.setAttribute(kl,d?"true":"false"),u.setAttribute(Gm,o),Zm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Xm(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let b=y("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",f.appendChild(b),u.appendChild(f);let T=y("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");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),u.appendChild(T),o!=="rows"&&u.appendChild(Ym(r,o)),Ll(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Dy=(e,t,n)=>{let{payload:r}=Xr(t),o=Math.max(1,ha(r).length);o>Ws(e)&&(e.setAttribute(Ml,String(o)),o>1&&!To(e)&&e.setAttribute(kl,"true")),Ll(e,t,n)},ng=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=ei(t);Xm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=Xr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Hs=(e,t,n)=>{if(!n||!Jr(e)||ei(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Rs}]`).forEach(c=>{c.getAttribute(Rs)!==o&&c.remove()});let a=n.querySelector(`[${Rs}="${Jm(o)}"]`);if(a){Dy(a,e,t);return}let{payload:i}=Xr(e),d=By(e,t,i);n.appendChild(d)},Eo=(e,t)=>{if(!e)return;let n=t?`[${Rs}="${Jm(t)}"]`:`[${Rs}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Pl=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=os(e),r=rr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Zm(e,n),eg(e),tg(e)},ni=(e,t,n,r)=>{let o=Ws(e),s=Math.max(0,Math.min(o-1,r));Ry(e,s),Ll(e,t,n)};var br="suggest_replies";var Il={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ri={name:br,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:Il,origin:"sdk",annotations:{readOnlyHint:!0}},Rl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ya=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===br},Wl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},oi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!ya(r))continue;let o=Wl((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},rg=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Hl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ga,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},Bl={name:fa,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:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},ba=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Bl),rg(e)&&t.push(ri),t};var Qr=require("partial-json"),si=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ko=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)}},Ny=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},og=e=>e.status==="complete"?Ny(e):e.status==="pending"?"Waiting":"",Oy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var sg=e=>e.status==="complete"?Oy(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},va=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},ii=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},Dl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=va(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},li=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&xa(r,n.slice(s,a.index),[]),a[1]!==void 0?xa(r,a[1],["bold"]):a[2]!==void 0?xa(r,a[2],["italic"]):a[3]!==void 0&&xa(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&xa(r,n.slice(s),[]),r},xa=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Fy=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${e.description}`:"");return window.confirm(n)},Ey=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)}},My=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ky=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Ly="agent_",Py="flow_";function eg(e){return e.startsWith(Ly)?{kind:"agentId",agentId:e}:e.startsWith(Py)?{kind:"flowId",flowId:e}:null}function tg(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=eg(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)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:d(i).payload}}let o=eg(n);if(o)return o;let s=t==null?void 0: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 Eo=require("partial-json");var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Dr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Mt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},ya=(...e)=>e.filter(Boolean).join(" ");var xa="ask_user_question",ba=8,Bs="data-persona-ask-sheet-for",Iy="Other",Ry="Other\u2026",rg="Type your own answer here",og="Send",Wy="Next",Hy="Back",By="Submit all",Dy="Skip",Ny=3,Hl="data-ask-current-index",Bl="data-ask-question-count",sg="data-ask-answers",Dl="data-ask-grouped",ag="data-ask-layout",Oy=e=>e.layout==="pills"?"pills":"rows",Fy=e=>e.getAttribute(ag)==="pills"?"pills":"rows",ng=!1,ig=e=>e.replace(/["\\]/g,"\\$&"),Yr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xa,si=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Zr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,Eo.parse)(o,Eo.STR|Eo.OBJ|Eo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},va=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ba&&!ng&&(ng=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ba}.`)),t.slice(0,ba)},_y=e=>{var t;return(t=va(e)[0])!=null?t:null},$y=(e,t)=>{var n;return(n=va(e)[t])!=null?n:null},lg=(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))},cg=(e,t,n)=>{if(e!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},jy=(e,t,n,r)=>{let s=b("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",r?"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=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=b("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=cg(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Uy=e=>{let n=b("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},qy=(e,t,n,r)=>{var p,u,f;let s=b("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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Ny;g++)s.appendChild(Uy(r));return s}if(d.forEach((g,y)=>{s.appendChild(jy(g,y,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Iy:Ry;if(r==="rows"){let y=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=t.freeTextPlaceholder)!=null?p:rg,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(S),y.appendChild(v);let E=cg(r,a,d.length);E&&y.appendChild(E),s.appendChild(y)}else{let y=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(y)}}return s},dg=(e,t)=>{var s,a;let r=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:rg,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:og,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},zy=e=>{var r;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:og,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Vy=(e,t,n)=>{var c,p,u,f;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:Hy,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Dy,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:By:(f=n.nextLabel)!=null?f:Wy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},as=e=>{let t=e.getAttribute(sg);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},pg=(e,t)=>{e.setAttribute(sg,JSON.stringify(t))},rr=e=>{var n;let t=Number((n=e.getAttribute(Hl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ky=(e,t)=>{e.setAttribute(Hl,String(Math.max(0,Math.floor(t))))},Ds=e=>{var n;let t=Number((n=e.getAttribute(Bl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Mo=e=>e.getAttribute(Dl)==="true",Gy=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Jy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ai=(e,t)=>{let{payload:n}=Zr(t),r=va(n),o=as(e),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},ug=e=>{let t=as(e),n=rr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},mg=e=>{if(!Mo(e))return;let t=as(e),n=rr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},Nl=(e,t,n)=>{let r=si(n),o=Fy(e),{payload:s,complete:a}=Zr(t),i=Mo(e),d=rr(e),c=Ds(e),p=i?$y(s,d):_y(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let P=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=P,y.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let P=qy(p,r,a,o);v.replaceWith(P)}if(o!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(dg(r,o))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?e.appendChild(zy(r)):(!u||i)&&S&&S.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=Vy(d,c,r);E?E.replaceWith(P):e.appendChild(P)}else E&&E.remove();ug(e),mg(e)},Xy=(e,t,n)=>{let r=si(t),o=Oy(r),s=e.toolCall.id,a=va(n),i=Math.max(1,a.length),d=i>1,c=Gy(e,a),p=d?Jy(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Bs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Bl,String(i)),u.setAttribute(Hl,String(p)),u.setAttribute(Dl,d?"true":"false"),u.setAttribute(ag,o),pg(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),lg(u,r);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let y=b("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),u.appendChild(f);let S=b("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");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),u.appendChild(S),o!=="rows"&&u.appendChild(dg(r,o)),Nl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Qy=(e,t,n)=>{let{payload:r}=Zr(t),o=Math.max(1,va(r).length);o>Ds(e)&&(e.setAttribute(Bl,String(o)),o>1&&!Mo(e)&&e.setAttribute(Dl,"true")),Nl(e,t,n)},gg=(e,t)=>{let n=b("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=si(t);lg(n,r);let o=b("span","persona-ask-stub-label"),{complete:s}=Zr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ns=(e,t,n)=>{if(!n||!Yr(e)||si(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Bs}]`).forEach(c=>{c.getAttribute(Bs)!==o&&c.remove()});let a=n.querySelector(`[${Bs}="${ig(o)}"]`);if(a){Qy(a,e,t);return}let{payload:i}=Zr(e),d=Xy(e,t,i);n.appendChild(d)},ko=(e,t)=>{if(!e)return;let n=t?`[${Bs}="${ig(t)}"]`:`[${Bs}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Ol=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Lo=(e,t)=>{let n=as(e),r=rr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,pg(e,n),ug(e),mg(e)},ii=(e,t,n,r)=>{let o=Ds(e),s=Math.max(0,Math.min(o-1,r));Ky(e,s),Nl(e,t,n)};var yr="suggest_replies";var Fl={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},li={name:yr,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:Fl,origin:"sdk",annotations:{readOnlyHint:!0}},_l=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===yr},$l=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},ci=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!wa(r))continue;let o=$l((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},fg=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var jl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ba,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},Ul={name:xa,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:jl,origin:"sdk",annotations:{readOnlyHint:!0}},Os=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Ul),fg(e)&&t.push(li),t};var eo=require("partial-json"),di=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Po=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)}},Yy=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},hg=e=>e.status==="complete"?Yy(e):e.status==="pending"?"Waiting":"",Zy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var yg=e=>e.status==="complete"?Zy(e):"Using tool...",pi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Aa=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return pi(t)},ui=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return pi(t)},ql=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Aa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},mi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Ca(r,n.slice(s,a.index),[]),a[1]!==void 0?Ca(r,a[1],["bold"]):a[2]!==void 0?Ca(r,a[2],["italic"]):a[3]!==void 0&&Ca(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ca(r,n.slice(s),[]),r},Ca=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},eb=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.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 r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},wa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=Fy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},pi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Qr.parse)(n,Qr.STR|Qr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?si(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=si(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ag=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?si(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?si(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,Qr.parse)(s,Qr.STR|Qr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ui=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ig="4.6.0";var or=ig;var $y="https://api.runtype.com/v1/dispatch",mi="https://api.runtype.com";function jy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Nl=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 Uy(e){switch(e){case"json":return pi;case"regex-json":return di;case"xml":return ui;default:return ci}}var lg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function qy(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lg(n);if(!lg(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=wa(e);return wa(t)!==null&&a===null?t:e}var ss=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;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=(n=t.apiUrl)!=null?n:$y,this.headers={"Content-Type":"application/json","X-Persona-Version":or,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Uy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Is(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Um(r,o);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){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Nl).map(M=>{var L,C,R;return{id:M.id,role:M.role,content:(R=(C=(L=M.contentParts)!=null?L:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?$m(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,T=g&&v&&this.lastSentClientToolsFingerprint===b,E=!1,P=null,I;for(let M=0;;M++){let C={...u,...g&&(E||!T)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),I=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(C),signal:r.signal}),I.status===409&&M===0&&g){let R=await I.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=R!=null?R:{error:"Chat request failed"}}break}if(!I.ok){let M=P!=null?P:await I.json().catch(()=>({error:"Chat request failed"}));if(I.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(I.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let L=new Error(M.error||"Failed to send message");throw n({type:"error",error:L}),L}if(!I.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(I.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||mi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Nl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Nl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{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(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var hn,vr,wr,qe;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=k=>{let me=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,Ee=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,Le=k.tools?k.tools.map(Be=>({...Be,chunks:Be.chunks?[...Be.chunks]:void 0})):void 0;return{...k,reasoning:me,toolCall:Ee,tools:Le}},f=k=>{if(k.role!=="assistant"||k.variant)return!0;let me=Array.isArray(k.contentParts)&&k.contentParts.length>0,Ee=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||me||Ee||!!k.stopReason},g=k=>{f(k)&&n({type:"message",message:u(k)})},b=null,v=null,T={current:null},E={current:null},P=null,I="",M=new Map,L=new Map,C=new Map,R=new Map,U=new Map,j={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},O=k=>{if(k==null)return null;try{return String(k)}catch{return null}},F=k=>{var me,Ee,Le,Be,rt;return O((rt=(Be=(Le=(Ee=(me=k.stepId)!=null?me:k.step_id)!=null?Ee:k.step)!=null?Le:k.parentId)!=null?Be:k.flowStepId)!=null?rt:k.flow_step_id)},ee=k=>{var me,Ee,Le,Be,rt,Ye,yt;return O((yt=(Ye=(rt=(Be=(Le=(Ee=(me=k.callId)!=null?me:k.call_id)!=null?Ee:k.requestId)!=null?Le:k.request_id)!=null?Be:k.toolCallId)!=null?rt:k.tool_call_id)!=null?Ye:k.stepId)!=null?yt:k.step_id)},Me=r,pe=!1,te=()=>{if(b)return b;let k,me="",Ee=P;return!pe&&Me?(k=Me,pe=!0,me=o!=null?o:""):Me&&Ee?k=`${Me}_${Ee}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:k,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Pe=(k,me)=>{j.lastId=me,k&&j.byStep.set(k,me)},Ie=(k,me)=>{var rt;let Ee=(rt=k.reasoningId)!=null?rt:k.id,Le=F(k);if(Ee){let Ye=String(Ee);return Pe(Le,Ye),Ye}if(Le){let Ye=j.byStep.get(Le);if(Ye)return j.lastId=Ye,Ye}if(j.lastId&&!me)return j.lastId;if(!me)return null;let Be=`reason-${p()}`;return Pe(Le,Be),Be},re=k=>{let me=R.get(k);if(me)return me;let Ee={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:k,status:"streaming",chunks:[]}};return R.set(k,Ee),g(Ee),Ee},Se=(k,me)=>{W.lastId=me,k&&W.byCall.set(k,me)},oe=new Set,ae=new Map,ie=new Set,ye=new Map,je=k=>{if(!k)return!1;let me=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},K=(k,me)=>{var rt;let Ee=(rt=k.toolId)!=null?rt:k.id,Le=ee(k);if(Ee){let Ye=String(Ee);return Se(Le,Ye),Ye}if(Le){let Ye=W.byCall.get(Le);if(Ye)return W.lastId=Ye,Ye}if(W.lastId&&!me)return W.lastId;if(!me)return null;let Be=`tool-${p()}`;return Se(Le,Be),Be},Y=k=>{let me=U.get(k);if(me)return me;let Ee={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:k,status:"pending"}};return U.set(k,Ee),g(Ee),Ee},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let me=Number(k);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Ee=Date.parse(k);if(!Number.isNaN(Ee))return Ee}return Date.now()},X=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},ce=new Map,Re=new Map,be=new Map,Ge=(k,me,Ee)=>{var yt;let Le=be.get(k);Le||(Le=[],be.set(k,Le));let Be=0,rt=Le.length;for(;Be<rt;){let ge=Be+rt>>>1;Le[ge].seq<me?Be=ge+1:rt=ge}((yt=Le[Be])==null?void 0:yt.seq)===me?Le[Be]={seq:me,text:Ee}:Le.splice(Be,0,{seq:me,text:Ee});let Ye="";for(let ge=0;ge<Le.length;ge++)Ye+=Le[ge].text;return Ye},ft=(k,me)=>{let Ee=X(me),Le=Re.get(k.id),Be=qy(Le,Ee);k.rawContent=Be;let rt=ce.get(k.id),Ye=de=>{var Xe;let ht=(Xe=k.content)!=null?Xe:"";de.trim()!==""&&(ht.trim().length===0||de.startsWith(ht)||de.trimStart().startsWith(ht.trim()))&&(k.content=de)},yt=()=>{var de;if(rt){let ht=(de=rt.close)==null?void 0:de.call(rt);ht instanceof Promise&&ht.catch(()=>{})}ce.delete(k.id),Re.delete(k.id),k.streaming=!1,g(k)};if(!rt){Ye(Ee),yt();return}let ge=wa(Be);if(ge!==null&&ge.trim()!==""){Ye(ge),yt();return}let D=de=>{var Pt;let ht=typeof de=="string"?de:(Pt=de==null?void 0:de.text)!=null?Pt:null;if(ht!==null&&ht.trim()!=="")return ht;let Xe=rt.getExtractedText();return Xe!==null&&Xe.trim()!==""?Xe:Ee},ve;try{ve=rt.processChunk(Be)}catch{Ye(Ee),yt();return}if(ve instanceof Promise){ve.then(de=>{Ye(D(de)),yt()}).catch(()=>{Ye(Ee),yt()});return}Ye(D(ve)),yt()},Ht=null,nt=(k,me,Ee,Le)=>{var ge;k.rawContent=me,ce.has(k.id)||ce.set(k.id,this.createStreamParser());let Be=ce.get(k.id),rt=me.trim().startsWith("{")||me.trim().startsWith("[");if(rt&&Re.set(k.id,me),Be.__isPlainTextParser===!0){k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k);return}let yt=Be.processChunk(me);if(yt instanceof Promise)yt.then(D=>{var de;let ve=typeof D=="string"?D:(de=D==null?void 0:D.text)!=null?de:null;ve!==null&&ve.trim()!==""?(k.content=ve,g(k)):!rt&&!me.trim().startsWith("<")&&(k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k)});else{let D=typeof yt=="string"?yt:(ge=yt==null?void 0:yt.text)!=null?ge:null;D!==null&&D.trim()!==""?(k.content=D,g(k)):!rt&&!me.trim().startsWith("<")&&(k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k))}},fe=(k,me)=>{var ge,D;let Ee=me!=null?me:k.content;if(Ee==null||Ee===""){k.streaming=!1,g(k);return}let Le=Re.get(k.id),Be=Le!=null?Le:X(Ee);k.rawContent=Be;let rt=ce.get(k.id),Ye=null,yt=!1;if(rt&&(Ye=rt.getExtractedText(),Ye===null&&(Ye=wa(Be)),Ye===null)){let ve=rt.processChunk(Be);ve instanceof Promise?(yt=!0,ve.then(de=>{var Xe;let ht=typeof de=="string"?de:(Xe=de==null?void 0:de.text)!=null?Xe:null;ht!==null&&(k.content=ht,k.streaming=!1,ce.delete(k.id),Re.delete(k.id),g(k))}).catch(()=>{})):Ye=typeof ve=="string"?ve:(ge=ve==null?void 0:ve.text)!=null?ge:null}if(!yt){Ye!==null&&Ye.trim()!==""?k.content=Ye:Re.has(k.id)||(k.content=X(Ee));let ve=ce.get(k.id);if(ve){let de=(D=ve.close)==null?void 0:D.call(ve);de instanceof Promise&&de.catch(()=>{}),ce.delete(k.id)}Re.delete(k.id),k.streaming=!1,g(k)}},Q=(k,me,Ee)=>{let Le=L.get(k);if(Le)return Le;let Be={id:`nested-${me}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return L.set(k,Be),g(Be),Be},lt=[],Ke,Te=new Map,Ce=0,et="agent",zt=!1,xe=null,ue=null,wn=new Map,At=(hn=this.config.iterationDisplay)!=null?hn:"separate";for(Ke=()=>{var k,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,tn,Cr,Fr,ar,ir,no,Vt,lr,_r,Bn,Ln,Dn,cr,Ar,ro,Gn,oo,St,Sr,Tr,$r,dr,bt,Fo,Er,_o,Pn,fs,so,jr,ao,io,$o,jo,lo,wt,Nn,On,Cn,Tt,Jn,Xn,Fn,co,Ae,Ur,Qn,_t,Yn,qr,Qs,hs,Ys,Uo,Mr,po,ct,sn,an,kr,Zs,zr,qo,Lr,_,ys,pr,Pr,Vr,Ir,ur,bs,qa,yn,An,mr,Sn,zo,gr,bn,Rr,xs,Vo,vs,uo;for(let mo=0;mo<lt.length;mo++){let st=lt[mo].payloadType,w=lt[mo].payload;if(!zt&&et!=="flow"&&typeof w.stepType=="string"&&(et="flow"),st==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){M.set(V,z),Q(V,z,"reasoning");continue}let J=(k=Ie(w,!0))!=null?k:`reason-${p()}`,G=re(J);G.reasoning=(me=G.reasoning)!=null?me:{id:J,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:ke((Ee=w.startedAt)!=null?Ee:w.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),G.streaming=!0,G.reasoning.status="streaming",g(G)}else if(st==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)&&L.has(V)){let Oe=L.get(V),ot=(Ye=(rt=(Be=w.reasoningText)!=null?Be:w.text)!=null?rt:w.delta)!=null?Ye:"";ot&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(ot)),g(Oe));continue}let z=(ge=(yt=Ie(w,!1))!=null?yt:Ie(w,!0))!=null?ge:`reason-${p()}`,J=re(z);J.reasoning=(D=J.reasoning)!=null?D:{id:z,status:"streaming",chunks:[]},J.reasoning.startedAt=(de=J.reasoning.startedAt)!=null?de:ke((ve=w.startedAt)!=null?ve:w.timestamp);let G=(Pt=(Xe=(ht=w.reasoningText)!=null?ht:w.text)!=null?Xe:w.delta)!=null?Pt:"";if(G&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let ot=Ge(z,Oe,String(G));J.reasoning.chunks=[ot]}else J.reasoning.chunks.push(String(G))}if(J.reasoning.status=w.done?"complete":"streaming",w.done){J.reasoning.completedAt=ke((kt=w.completedAt)!=null?kt:w.timestamp);let Oe=(vt=J.reasoning.startedAt)!=null?vt:Date.now();J.reasoning.durationMs=Math.max(0,((Wt=J.reasoning.completedAt)!=null?Wt:Date.now())-Oe)}J.streaming=J.reasoning.status!=="complete",g(J)}else if(st==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)&&L.has(V)){let ot=L.get(V);if(ot.reasoning){let dt=typeof w.text=="string"?w.text:"";dt&&ot.reasoning.chunks.length===0&&ot.reasoning.chunks.push(dt),ot.reasoning.status="complete",ot.streaming=!1,g(ot)}M.delete(V),L.delete(V);continue}let z=(Ft=(Qt=Ie(w,!1))!=null?Qt:Ie(w,!0))!=null?Ft:`reason-${p()}`,J=typeof w.text=="string"?w.text:"";!R.get(z)&&(J||w.scope==="loop")&&re(z);let G=R.get(z);if(G!=null&&G.reasoning){(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),J&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(J),G.reasoning.status="complete",G.reasoning.completedAt=ke((tn=w.completedAt)!=null?tn:w.timestamp);let ot=(Cr=G.reasoning.startedAt)!=null?Cr:Date.now();G.reasoning.durationMs=Math.max(0,((Fr=G.reasoning.completedAt)!=null?Fr:Date.now())-ot),G.streaming=!1,g(G)}let Oe=F(w);Oe&&j.byStep.delete(Oe)}else if(st==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(ir=(ar=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?ar:K(w,!0))!=null?ir:`tool-${p()}`,z=(no=w.toolName)!=null?no:w.name;if(je(z)){oe.add(V);continue}Se(ee(w),V);let J=Y(V),G=(Vt=J.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=z!=null?z:G.name,G.status="running",w.parameters!==void 0?G.args=w.parameters:w.args!==void 0&&(G.args=w.args),G.startedAt=(_r=G.startedAt)!=null?_r:ke((lr=w.startedAt)!=null?lr:w.timestamp),G.completedAt=void 0,G.durationMs=void 0,J.toolCall=G,J.streaming=!0,w.executionId&&(J.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(J)}else if(st==="tool_output_delta"){let V=(Ln=(Bn=K(w,!1))!=null?Bn:K(w,!0))!=null?Ln:`tool-${p()}`;if(oe.has(V))continue;let z=Y(V),J=(Dn=z.toolCall)!=null?Dn:{id:V,status:"running"};J.startedAt=(Ar=J.startedAt)!=null?Ar:ke((cr=w.startedAt)!=null?cr:w.timestamp);let G=(oo=(Gn=(ro=w.text)!=null?ro:w.delta)!=null?Gn:w.message)!=null?oo:"";G&&(J.chunks=(St=J.chunks)!=null?St:[],J.chunks.push(String(G))),J.status="running",z.toolCall=J,z.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=($r=z.agentMetadata)!=null?$r:{executionId:(Sr=Oe==null?void 0:Oe.executionId)!=null?Sr:w.executionId,iteration:(Tr=Oe==null?void 0:Oe.iteration)!=null?Tr:w.iteration}),g(z)}else if(st==="tool_complete"){let V=(bt=(dr=K(w,!1))!=null?dr:K(w,!0))!=null?bt:`tool-${p()}`;if(oe.has(V)){oe.delete(V);continue}let z=Y(V),J=(Fo=z.toolCall)!=null?Fo:{id:V,status:"running"};J.status="complete",w.result!==void 0&&(J.result=w.result),typeof w.duration=="number"&&(J.duration=w.duration),J.completedAt=ke((Er=w.completedAt)!=null?Er:w.timestamp);let G=(_o=w.duration)!=null?_o:w.executionTime;if(typeof G=="number")J.durationMs=G;else{let dt=(Pn=J.startedAt)!=null?Pn:Date.now();J.durationMs=Math.max(0,((fs=J.completedAt)!=null?fs:Date.now())-dt)}z.toolCall=J,z.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=(ao=z.agentMetadata)!=null?ao:{executionId:(so=Oe==null?void 0:Oe.executionId)!=null?so:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g(z);let ot=ee(w);ot&&W.byCall.delete(ot)}else if(st==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,z=(io=V!=null?V:w.toolId)!=null?io:`local-${p()}`,J=Y(z),G=w.toolName,Oe=w.origin==="webmcp"&&!Ao(G)?`webmcp:${G}`:G,ot=Ao(Oe),dt=($o=J.toolCall)!=null?$o:{id:z,status:"pending"};dt.name=Oe,dt.args=w.parameters,dt.status=ot?"running":"complete",dt.chunks=(jo=dt.chunks)!=null?jo:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:ke((wt=(lo=w.startedAt)!=null?lo:w.timestamp)!=null?wt:w.awaitedAt),ot?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(On=dt.completedAt)!=null?On:dt.startedAt,J.toolCall=dt,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(Tt=w.executionId)!=null?Tt:(Cn=J.agentMetadata)==null?void 0:Cn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(J)}else if(st==="text_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){M.set(V,z);continue}let J=b;J&&(et==="flow"?(fe(J),Ht=J):(J.streaming=!1,g(J)),b=null),P=typeof w.id=="string"?w.id:P,I=""}else if(st==="text_delta"){let V=typeof w.id=="string"?w.id:null,z=V?M.get(V):void 0;if(V&&z){let G=typeof w.delta=="string"?w.delta:"",Oe=((Jn=C.get(V))!=null?Jn:"")+G;if(C.set(V,Oe),Oe.trim()==="")continue;let ot=Q(V,z);ot.agentMetadata={...ot.agentMetadata,executionId:w.executionId,parentToolId:z},nt(ot,Oe,G,void 0);continue}if(P=typeof w.id=="string"?w.id:P,et==="flow"){let G=typeof w.delta=="string"?w.delta:"";if(I+=G,I.trim()==="")continue;let Oe=te();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},nt(Oe,I,G,void 0),v=Oe;continue}let J=te();J.content+=(Xn=w.delta)!=null?Xn:"",J.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:xe!=null?xe:void 0,agentName:ue==null?void 0:ue.agentName},v=J,g(J)}else if(st==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)){let J=L.get(V);J&&fe(J),M.delete(V),C.delete(V),L.delete(V);continue}let z=b;z&&(et==="flow"?(fe(z),Ht=z):(((Fn=z.content)!=null?Fn:"")===""&&typeof w.text=="string"&&(z.content=w.text),z.streaming=!1,g(z)),b=null),P=null,I=""}else if(st==="step_complete"){let V=w.stepType,z=w.executionType;if(V==="tool"||z==="context")continue;if(w.success===!1){let J=w.error,G=typeof J=="string"&&J!==""?J:J!=null&&typeof J=="object"&&"message"in J?String((co=J.message)!=null?co:"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let Oe=b;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),n({type:"status",status:"idle"});continue}{let J=Ht;Ht=null;let G=w.stopReason,Oe=(Ae=w.result)==null?void 0:Ae.response;if(J)G&&(J.stopReason=G),Oe!=null?ft(J,Oe):J.streaming!==!1&&(ce.delete(J.id),Re.delete(J.id),J.streaming=!1,g(J));else{let ot=Oe!=null&&Oe!=="";if(ot||G){let dt=te();G&&(dt.stopReason=G),ot?fe(dt,Oe):(dt.streaming=!1,g(dt))}}continue}}else if(st==="execution_start")et=w.kind==="flow"?"flow":"agent",zt=!0,et==="agent"&&(ue={executionId:w.executionId,agentId:(Ur=w.agentId)!=null?Ur:"virtual",agentName:(Qn=w.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=w.maxTurns)!=null?_t:1,startedAt:ke(w.startedAt)});else if(st==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let z=b;z&&(z.streaming=!1,g(z),wn.set(V-1,z),b=null)}Ce=V}xe=typeof w.id=="string"?w.id:null,v=null}else if(st==="tool_input_delta"){let V=(Yn=w.toolCallId)!=null?Yn:W.lastId;if(V){let z=U.get(V);z!=null&&z.toolCall&&(z.toolCall.chunks=(qr=z.toolCall.chunks)!=null?qr:[],z.toolCall.chunks.push((Qs=w.delta)!=null?Qs:""),g(z))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=w.stopReason,z=b!=null?b:v;if(V&&z!==null){let J=w.id;(!J||((hs=z.agentMetadata)==null?void 0:hs.turnId)===J)&&(z.stopReason=V,g(z))}xe===w.id&&(xe=null)}else if(st==="media_start"){let V=String(w.id);Te.set(V,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Te.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(st==="media_complete"){let V=String(w.id),z=Te.get(V);Te.delete(V);let J=(Uo=(Ys=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ys:z==null?void 0:z.mediaType)!=null?Uo:"application/octet-stream",G=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:z&&z.parts.length>0?z.parts.join(""):void 0,ot=null;if(G)ot={type:"media",data:G,mediaType:J};else if(Oe){let In=J.toLowerCase();ot={type:In==="image"||In.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:J}}let dt=(Mr=w.toolCallId)!=null?Mr:z==null?void 0:z.toolCallId,pl=ot?[ot]:[],go=[];for(let In of pl){if(!In||typeof In!="object")continue;let Yt=In,fo=typeof Yt.type=="string"?Yt.type:void 0,Zn=typeof Yt.mediaType=="string"?Yt.mediaType.toLowerCase():"",Tn=null,Rn="";if(fo==="media"){let En=typeof Yt.data=="string"?Yt.data:void 0;if(!En)continue;Rn=Zn.length>0?Zn:"application/octet-stream",Tn=`data:${Rn};base64,${En}`}else if(fo==="image-url"){let En=typeof Yt.url=="string"?Yt.url:void 0;if(!En)continue;Rn=Zn,Tn=En}else if(fo==="file-url"){let En=typeof Yt.url=="string"?Yt.url:void 0;if(!En)continue;Rn=Zn,Tn=En}else continue;if(Tn)if(fo==="image-url"||Rn.startsWith("image/"))go.push({type:"image",image:Tn,...Rn.includes("/")?{mimeType:Rn}:{}});else if(Rn.startsWith("audio/"))go.push({type:"audio",audio:Tn,mimeType:Rn});else if(Rn.startsWith("video/"))go.push({type:"video",video:Tn,mimeType:Rn});else{let En=Rn||"application/octet-stream";go.push({type:"file",data:Tn,mimeType:En,filename:jy(En)})}}if(go.length>0){let In=p(),Yt=dt,Zn={id:`agent-media-${typeof Yt=="string"&&Yt.length>0?`${Yt}-${In}`:String(In)}`,role:"assistant",content:"",contentParts:go,createdAt:new Date().toISOString(),streaming:!1,sequence:In,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Zn);let Tn=b;Tn&&(Tn.streaming=!1,g(Tn)),b=null,T.current=null}}else if(st==="execution_complete"){let V=(po=w.kind)!=null?po:et;V==="agent"&&ue&&(ue.status=w.success?"complete":"error",ue.completedAt=ke(w.completedAt),ue.stopReason=w.stopReason);let z=b;z&&(V==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,g(z)),b=null),P=null,I="",Ht=null,n({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof w.error=="string"?w.error:(sn=(ct=w.error)==null?void 0:ct.message)!=null?sn:"Execution error";n({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(an=w.approvalId)!=null?an:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(kr=ue==null?void 0:ue.agentId)!=null?kr:"virtual",executionId:(zr=(Zs=w.executionId)!=null?Zs:ue==null?void 0:ue.executionId)!=null?zr:"",toolName:(qo=w.toolName)!=null?qo:"",toolType:w.toolType,description:(_=w.description)!=null?_:`Execute ${(Lr=w.toolName)!=null?Lr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="step_await"&&w.awaitReason==="approval_required"){let V=(ys=w.approvalId)!=null?ys:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(pr=ue==null?void 0:ue.agentId)!=null?pr:"virtual",executionId:(Vr=(Pr=w.executionId)!=null?Pr:ue==null?void 0:ue.executionId)!=null?Vr:"",toolName:(Ir=w.toolName)!=null?Ir:"",toolType:w.toolType,description:(bs=w.description)!=null?bs:`Execute ${(ur=w.toolName)!=null?ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="approval_complete"){let V=w.approvalId;if(V){let J={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(qa=w.decision)!=null?qa:"approved",agentId:(yn=ue==null?void 0:ue.agentId)!=null?yn:"virtual",executionId:(mr=(An=w.executionId)!=null?An:ue==null?void 0:ue.executionId)!=null?mr:"",toolName:(Sn=w.toolName)!=null?Sn:"",description:(zo=w.description)!=null?zo:"",resolvedAt:Date.now()}};g(J)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=w.artifactType,z=String(w.id),J=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:z,artifactType:V,title:J,component:typeof w.component=="string"?w.component:void 0}),ye.set(z,{markdown:"",title:J}),!ie.has(z)){ie.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:J,artifactType:V,status:"streaming"}})};ae.set(z,G),g(G)}}else if(st==="artifact_delta"){let V=String(w.id),z=typeof w.delta=="string"?w.delta:String((gr=w.delta)!=null?gr:"");n({type:"artifact_delta",id:V,artDelta:z});let J=ye.get(V);J&&(J.markdown+=z)}else if(st==="artifact_update"){let V=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:V,component:typeof w.component=="string"?w.component:void 0})}else if(st==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let z=ae.get(V);if(z){z.streaming=!1;try{let J=JSON.parse((bn=z.rawContent)!=null?bn:"{}");if(J.props){J.props.status="complete";let G=ye.get(V);G!=null&&G.markdown&&(J.props.markdown=G.markdown)}z.rawContent=JSON.stringify(J)}catch{}ye.delete(V),g(z),ae.delete(V)}}}else if(st==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let z=String((Rr=V.id)!=null?Rr:`msg-${p()}`),J=V.role,Oe={id:z,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:p()};if(g(Oe),Oe.rawContent)try{let ot=JSON.parse(Oe.rawContent),dt=(xs=ot==null?void 0:ot.props)==null?void 0:xs.artifactId;typeof dt=="string"&&ie.add(dt)}catch{}b=null,T.current=null,ce.delete(z),Re.delete(z)}else if(st==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((Vo=w.error)==null?void 0:Vo.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let z=b;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(st==="dispatch_error"){let z=(vs=w.message)!=null?vs:w.error;z!=null&&z!==""&&(V=new Error(String(z)))}else{let z=w.error;typeof z=="string"&&z!==""?V=new Error(z):z!=null&&typeof z=="object"&&"message"in z&&(V=new Error(String((uo=z.message)!=null?uo:z)))}if(V){n({type:"error",error:V});let z=b;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:k,value:me}=await s.read();if(k)break;i+=a.decode(me,{stream:!0});let Ee=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Sa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},gi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},fi=()=>{var t;let e=eb();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},hi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,eo.parse)(n,eo.STR|eo.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?di(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=di(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},bg=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?di(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?di(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,eo.parse)(s,eo.STR|eo.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},yi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var xg="4.7.0";var or=xg;var nb="https://api.runtype.com/v1/dispatch",bi="https://api.runtype.com";function rb(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var zl=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 ob(e){switch(e){case"json":return hi;case"regex-json":return fi;case"xml":return yi;default:return gi}}var vg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function sb(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=vg(n);if(!vg(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Sa(e);return Sa(t)!==null&&a===null?t:e}var is=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;var n,r,o,s;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=(n=t.apiUrl)!=null?n:nb,this.headers={"Content-Type":"application/json","X-Persona-Version":or,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:ob(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Hs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=tg(r,o);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){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||bi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||bi}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){var r;return(r=t.signal)==null||r.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,o,s,a;n({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(r=this.config).onSessionExpired)==null||o.call(r);let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}let d=await this.buildPayload(t.messages),c=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:i.sessionId,messages:t.messages.filter(zl).map(g=>{var y,v,S;return{id:g.id,role:g.role,content:(S=(v=(y=g.contentParts)!=null?y:g.llmContent)!=null?v:g.rawContent)!=null?S:g.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},{response:u,commit:f}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,g=>{let y={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",y),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(y),signal:t.signal})});if(!u.ok){let g=await u.json().catch(()=>({error:"Chat request failed"}));if(u.status===401){this.clearClientSession(),(a=(s=this.config).onSessionExpired)==null||a.call(s);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(u.status===429){let v=new Error(g.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let y=new Error(g.error||"Failed to send message");throw n({type:"error",error:y}),y}if(!u.body){let g=new Error("No response body received");throw n({type:"error",error:g}),g}f(),n({type:"status",status:"connected"});try{await this.streamResponse(u.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&n({type:"error",error:d}),d}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}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:o,body:JSON.stringify(r),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 r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}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:o,body:JSON.stringify(r),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,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||bi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,r,o){let s=!!(n&&n.length>0),a=s?Zm(n):void 0,i=this.clientToolsFingerprintSessionId===t,d=s&&i&&this.lastSentClientToolsFingerprint===a,c=!s&&(o==null?void 0:o.emptyMeansReplace)===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,u;for(let f=0;;f++){if(u=await r({...s&&(p||!d)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&f===0&&s){let y=await u.clone().json().catch(()=>null);if((y==null?void 0:y.error)==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a!=null?a:null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,r){var c,p,u,f;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||bi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};if(a&&(d.sessionId=a),o&&a){let g=[...Os(this.config),...(f=await((u=this.webMcpBridge)==null?void 0:u.snapshotForDispatch()))!=null?f:[]],{response:y,commit:v}=await this.sendWithClientToolsDiff(a,g,S=>{let E={...d,...S};return this.debug&&console.debug("[AgentWidgetClient] client token resume",E),fetch(s,{method:"POST",headers:i,body:JSON.stringify(E),signal:r==null?void 0:r.signal})},{emptyMeansReplace:!0});return y.ok&&v(),y}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(zl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Os(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(zl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Os(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{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(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var bn,xr,vr,qe;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let me=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Ee=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,Le=M.tools?M.tools.map(Be=>({...Be,chunks:Be.chunks?[...Be.chunks]:void 0})):void 0;return{...M,reasoning:me,toolCall:Ee,tools:Le}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let me=Array.isArray(M.contentParts)&&M.contentParts.length>0,Ee=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||me||Ee||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},y=null,v=null,S={current:null},E={current:null},P=null,H="",W=new Map,I=new Map,T=new Map,B=new Map,q=new Map,U={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},F=M=>{if(M==null)return null;try{return String(M)}catch{return null}},_=M=>{var me,Ee,Le,Be,rt;return F((rt=(Be=(Le=(Ee=(me=M.stepId)!=null?me:M.step_id)!=null?Ee:M.step)!=null?Le:M.parentId)!=null?Be:M.flowStepId)!=null?rt:M.flow_step_id)},ee=M=>{var me,Ee,Le,Be,rt,Ye,yt;return F((yt=(Ye=(rt=(Be=(Le=(Ee=(me=M.callId)!=null?me:M.call_id)!=null?Ee:M.requestId)!=null?Le:M.request_id)!=null?Be:M.toolCallId)!=null?rt:M.tool_call_id)!=null?Ye:M.stepId)!=null?yt:M.step_id)},Me=r,pe=!1,te=()=>{if(y)return y;let M,me="",Ee=P;return!pe&&Me?(M=Me,pe=!0,me=o!=null?o:""):Me&&Ee?M=`${Me}_${Ee}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:M,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(y),y},Pe=(M,me)=>{U.lastId=me,M&&U.byStep.set(M,me)},Ie=(M,me)=>{var rt;let Ee=(rt=M.reasoningId)!=null?rt:M.id,Le=_(M);if(Ee){let Ye=String(Ee);return Pe(Le,Ye),Ye}if(Le){let Ye=U.byStep.get(Le);if(Ye)return U.lastId=Ye,Ye}if(U.lastId&&!me)return U.lastId;if(!me)return null;let Be=`reason-${p()}`;return Pe(Le,Be),Be},re=M=>{let me=B.get(M);if(me)return me;let Ee={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return B.set(M,Ee),g(Ee),Ee},Se=(M,me)=>{L.lastId=me,M&&L.byCall.set(M,me)},oe=new Set,ae=new Map,ie=new Set,ye=new Map,je=M=>{if(!M)return!1;let me=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},K=(M,me)=>{var rt;let Ee=(rt=M.toolId)!=null?rt:M.id,Le=ee(M);if(Ee){let Ye=String(Ee);return Se(Le,Ye),Ye}if(Le){let Ye=L.byCall.get(Le);if(Ye)return L.lastId=Ye,Ye}if(L.lastId&&!me)return L.lastId;if(!me)return null;let Be=`tool-${p()}`;return Se(Le,Be),Be},Y=M=>{let me=q.get(M);if(me)return me;let Ee={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return q.set(M,Ee),g(Ee),Ee},ke=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let me=Number(M);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Ee=Date.parse(M);if(!Number.isNaN(Ee))return Ee}return Date.now()},X=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},ce=new Map,Re=new Map,be=new Map,Ge=(M,me,Ee)=>{var yt;let Le=be.get(M);Le||(Le=[],be.set(M,Le));let Be=0,rt=Le.length;for(;Be<rt;){let ge=Be+rt>>>1;Le[ge].seq<me?Be=ge+1:rt=ge}((yt=Le[Be])==null?void 0:yt.seq)===me?Le[Be]={seq:me,text:Ee}:Le.splice(Be,0,{seq:me,text:Ee});let Ye="";for(let ge=0;ge<Le.length;ge++)Ye+=Le[ge].text;return Ye},ft=(M,me)=>{let Ee=X(me),Le=Re.get(M.id),Be=sb(Le,Ee);M.rawContent=Be;let rt=ce.get(M.id),Ye=de=>{var Xe;let ht=(Xe=M.content)!=null?Xe:"";de.trim()!==""&&(ht.trim().length===0||de.startsWith(ht)||de.trimStart().startsWith(ht.trim()))&&(M.content=de)},yt=()=>{var de;if(rt){let ht=(de=rt.close)==null?void 0:de.call(rt);ht instanceof Promise&&ht.catch(()=>{})}ce.delete(M.id),Re.delete(M.id),M.streaming=!1,g(M)};if(!rt){Ye(Ee),yt();return}let ge=Sa(Be);if(ge!==null&&ge.trim()!==""){Ye(ge),yt();return}let D=de=>{var Pt;let ht=typeof de=="string"?de:(Pt=de==null?void 0:de.text)!=null?Pt:null;if(ht!==null&&ht.trim()!=="")return ht;let Xe=rt.getExtractedText();return Xe!==null&&Xe.trim()!==""?Xe:Ee},ve;try{ve=rt.processChunk(Be)}catch{Ye(Ee),yt();return}if(ve instanceof Promise){ve.then(de=>{Ye(D(de)),yt()}).catch(()=>{Ye(Ee),yt()});return}Ye(D(ve)),yt()},Ht=null,nt=(M,me,Ee,Le)=>{var ge;M.rawContent=me,ce.has(M.id)||ce.set(M.id,this.createStreamParser());let Be=ce.get(M.id),rt=me.trim().startsWith("{")||me.trim().startsWith("[");if(rt&&Re.set(M.id,me),Be.__isPlainTextParser===!0){M.content=Le!==void 0?me:M.content+Ee,Re.delete(M.id),ce.delete(M.id),M.rawContent=void 0,g(M);return}let yt=Be.processChunk(me);if(yt instanceof Promise)yt.then(D=>{var de;let ve=typeof D=="string"?D:(de=D==null?void 0:D.text)!=null?de:null;ve!==null&&ve.trim()!==""?(M.content=ve,g(M)):!rt&&!me.trim().startsWith("<")&&(M.content=Le!==void 0?me:M.content+Ee,Re.delete(M.id),ce.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=Le!==void 0?me:M.content+Ee,Re.delete(M.id),ce.delete(M.id),M.rawContent=void 0,g(M)});else{let D=typeof yt=="string"?yt:(ge=yt==null?void 0:yt.text)!=null?ge:null;D!==null&&D.trim()!==""?(M.content=D,g(M)):!rt&&!me.trim().startsWith("<")&&(M.content=Le!==void 0?me:M.content+Ee,Re.delete(M.id),ce.delete(M.id),M.rawContent=void 0,g(M))}},fe=(M,me)=>{var ge,D;let Ee=me!=null?me:M.content;if(Ee==null||Ee===""){M.streaming=!1,g(M);return}let Le=Re.get(M.id),Be=Le!=null?Le:X(Ee);M.rawContent=Be;let rt=ce.get(M.id),Ye=null,yt=!1;if(rt&&(Ye=rt.getExtractedText(),Ye===null&&(Ye=Sa(Be)),Ye===null)){let ve=rt.processChunk(Be);ve instanceof Promise?(yt=!0,ve.then(de=>{var Xe;let ht=typeof de=="string"?de:(Xe=de==null?void 0:de.text)!=null?Xe:null;ht!==null&&(M.content=ht,M.streaming=!1,ce.delete(M.id),Re.delete(M.id),g(M))}).catch(()=>{})):Ye=typeof ve=="string"?ve:(ge=ve==null?void 0:ve.text)!=null?ge:null}if(!yt){Ye!==null&&Ye.trim()!==""?M.content=Ye:Re.has(M.id)||(M.content=X(Ee));let ve=ce.get(M.id);if(ve){let de=(D=ve.close)==null?void 0:D.call(ve);de instanceof Promise&&de.catch(()=>{}),ce.delete(M.id)}Re.delete(M.id),M.streaming=!1,g(M)}},Q=(M,me,Ee)=>{let Le=I.get(M);if(Le)return Le;let Be={id:`nested-${me}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return I.set(M,Be),g(Be),Be},lt=[],Ke,Te=new Map,Ce=0,et="agent",zt=!1,xe=null,ue=null,An=new Map,At=(bn=this.config.iterationDisplay)!=null?bn:"separate";for(Ke=()=>{var M,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,en,wr,Fr,ar,ir,so,Vt,lr,_r,Bn,In,Dn,cr,Cr,ao,Gn,io,St,Ar,Sr,$r,dr,bt,$o,Tr,jo,Rn,ys,lo,jr,co,po,Uo,qo,uo,wt,Nn,On,Sn,Tt,Jn,Xn,Fn,mo,Ae,Ur,Qn,_t,Yn,qr,ta,bs,na,zo,Er,go,ct,on,sn,Mr,ra,zr,Vo,kr,$,xs,Zn,Lr,Vr,Pr,pr,vs,Ga,xn,Tn,ur,En,Ko,mr,vn,Ir,ws,Go,Cs,fo;for(let ho=0;ho<lt.length;ho++){let st=lt[ho].payloadType,w=lt[ho].payload;if(!zt&&et!=="flow"&&typeof w.stepType=="string"&&(et="flow"),st==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){W.set(V,z),Q(V,z,"reasoning");continue}let J=(M=Ie(w,!0))!=null?M:`reason-${p()}`,G=re(J);G.reasoning=(me=G.reasoning)!=null?me:{id:J,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:ke((Ee=w.startedAt)!=null?Ee:w.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),G.streaming=!0,G.reasoning.status="streaming",g(G)}else if(st==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&W.has(V)&&I.has(V)){let Oe=I.get(V),ot=(Ye=(rt=(Be=w.reasoningText)!=null?Be:w.text)!=null?rt:w.delta)!=null?Ye:"";ot&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(ot)),g(Oe));continue}let z=(ge=(yt=Ie(w,!1))!=null?yt:Ie(w,!0))!=null?ge:`reason-${p()}`,J=re(z);J.reasoning=(D=J.reasoning)!=null?D:{id:z,status:"streaming",chunks:[]},J.reasoning.startedAt=(de=J.reasoning.startedAt)!=null?de:ke((ve=w.startedAt)!=null?ve:w.timestamp);let G=(Pt=(Xe=(ht=w.reasoningText)!=null?ht:w.text)!=null?Xe:w.delta)!=null?Pt:"";if(G&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let ot=Ge(z,Oe,String(G));J.reasoning.chunks=[ot]}else J.reasoning.chunks.push(String(G))}if(J.reasoning.status=w.done?"complete":"streaming",w.done){J.reasoning.completedAt=ke((kt=w.completedAt)!=null?kt:w.timestamp);let Oe=(vt=J.reasoning.startedAt)!=null?vt:Date.now();J.reasoning.durationMs=Math.max(0,((Wt=J.reasoning.completedAt)!=null?Wt:Date.now())-Oe)}J.streaming=J.reasoning.status!=="complete",g(J)}else if(st==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&W.has(V)&&I.has(V)){let ot=I.get(V);if(ot.reasoning){let dt=typeof w.text=="string"?w.text:"";dt&&ot.reasoning.chunks.length===0&&ot.reasoning.chunks.push(dt),ot.reasoning.status="complete",ot.streaming=!1,g(ot)}W.delete(V),I.delete(V);continue}let z=(Ft=(Qt=Ie(w,!1))!=null?Qt:Ie(w,!0))!=null?Ft:`reason-${p()}`,J=typeof w.text=="string"?w.text:"";!B.get(z)&&(J||w.scope==="loop")&&re(z);let G=B.get(z);if(G!=null&&G.reasoning){(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),J&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(J),G.reasoning.status="complete",G.reasoning.completedAt=ke((en=w.completedAt)!=null?en:w.timestamp);let ot=(wr=G.reasoning.startedAt)!=null?wr:Date.now();G.reasoning.durationMs=Math.max(0,((Fr=G.reasoning.completedAt)!=null?Fr:Date.now())-ot),G.streaming=!1,g(G)}let Oe=_(w);Oe&&U.byStep.delete(Oe)}else if(st==="tool_start"){y&&(y.streaming=!1,g(y),y=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(ir=(ar=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?ar:K(w,!0))!=null?ir:`tool-${p()}`,z=(so=w.toolName)!=null?so:w.name;if(je(z)){oe.add(V);continue}Se(ee(w),V);let J=Y(V),G=(Vt=J.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=z!=null?z:G.name,G.status="running",w.parameters!==void 0?G.args=w.parameters:w.args!==void 0&&(G.args=w.args),G.startedAt=(_r=G.startedAt)!=null?_r:ke((lr=w.startedAt)!=null?lr:w.timestamp),G.completedAt=void 0,G.durationMs=void 0,J.toolCall=G,J.streaming=!0,w.executionId&&(J.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(J)}else if(st==="tool_output_delta"){let V=(In=(Bn=K(w,!1))!=null?Bn:K(w,!0))!=null?In:`tool-${p()}`;if(oe.has(V))continue;let z=Y(V),J=(Dn=z.toolCall)!=null?Dn:{id:V,status:"running"};J.startedAt=(Cr=J.startedAt)!=null?Cr:ke((cr=w.startedAt)!=null?cr:w.timestamp);let G=(io=(Gn=(ao=w.text)!=null?ao:w.delta)!=null?Gn:w.message)!=null?io:"";G&&(J.chunks=(St=J.chunks)!=null?St:[],J.chunks.push(String(G))),J.status="running",z.toolCall=J,z.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=($r=z.agentMetadata)!=null?$r:{executionId:(Ar=Oe==null?void 0:Oe.executionId)!=null?Ar:w.executionId,iteration:(Sr=Oe==null?void 0:Oe.iteration)!=null?Sr:w.iteration}),g(z)}else if(st==="tool_complete"){let V=(bt=(dr=K(w,!1))!=null?dr:K(w,!0))!=null?bt:`tool-${p()}`;if(oe.has(V)){oe.delete(V);continue}let z=Y(V),J=($o=z.toolCall)!=null?$o:{id:V,status:"running"};J.status="complete",w.result!==void 0&&(J.result=w.result),typeof w.duration=="number"&&(J.duration=w.duration),J.completedAt=ke((Tr=w.completedAt)!=null?Tr:w.timestamp);let G=(jo=w.duration)!=null?jo:w.executionTime;if(typeof G=="number")J.durationMs=G;else{let dt=(Rn=J.startedAt)!=null?Rn:Date.now();J.durationMs=Math.max(0,((ys=J.completedAt)!=null?ys:Date.now())-dt)}z.toolCall=J,z.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=(co=z.agentMetadata)!=null?co:{executionId:(lo=Oe==null?void 0:Oe.executionId)!=null?lo:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g(z);let ot=ee(w);ot&&L.byCall.delete(ot)}else if(st==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,z=(po=V!=null?V:w.toolId)!=null?po:`local-${p()}`,J=Y(z),G=w.toolName,Oe=w.origin==="webmcp"&&!To(G)?`webmcp:${G}`:G,ot=To(Oe),dt=(Uo=J.toolCall)!=null?Uo:{id:z,status:"pending"};dt.name=Oe,dt.args=w.parameters,dt.status=ot?"running":"complete",dt.chunks=(qo=dt.chunks)!=null?qo:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:ke((wt=(uo=w.startedAt)!=null?uo:w.timestamp)!=null?wt:w.awaitedAt),ot?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(On=dt.completedAt)!=null?On:dt.startedAt,J.toolCall=dt,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(Tt=w.executionId)!=null?Tt:(Sn=J.agentMetadata)==null?void 0:Sn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(J)}else if(st==="text_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){W.set(V,z);continue}let J=y;J&&(et==="flow"?(fe(J),Ht=J):(J.streaming=!1,g(J)),y=null),P=typeof w.id=="string"?w.id:P,H=""}else if(st==="text_delta"){let V=typeof w.id=="string"?w.id:null,z=V?W.get(V):void 0;if(V&&z){let G=typeof w.delta=="string"?w.delta:"",Oe=((Jn=T.get(V))!=null?Jn:"")+G;if(T.set(V,Oe),Oe.trim()==="")continue;let ot=Q(V,z);ot.agentMetadata={...ot.agentMetadata,executionId:w.executionId,parentToolId:z},nt(ot,Oe,G,void 0);continue}if(P=typeof w.id=="string"?w.id:P,et==="flow"){let G=typeof w.delta=="string"?w.delta:"";if(H+=G,H.trim()==="")continue;let Oe=te();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},nt(Oe,H,G,void 0),v=Oe;continue}let J=te();J.content+=(Xn=w.delta)!=null?Xn:"",J.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:xe!=null?xe:void 0,agentName:ue==null?void 0:ue.agentName},v=J,g(J)}else if(st==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&W.has(V)){let J=I.get(V);J&&fe(J),W.delete(V),T.delete(V),I.delete(V);continue}let z=y;z&&(et==="flow"?(fe(z),Ht=z):(((Fn=z.content)!=null?Fn:"")===""&&typeof w.text=="string"&&(z.content=w.text),z.streaming=!1,g(z)),y=null),P=null,H=""}else if(st==="step_complete"){let V=w.stepType,z=w.executionType;if(V==="tool"||z==="context")continue;if(w.success===!1){let J=w.error,G=typeof J=="string"&&J!==""?J:J!=null&&typeof J=="object"&&Reflect.has(J,"message")?String((mo=J.message)!=null?mo:"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let Oe=y;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),n({type:"status",status:"idle"});continue}{let J=Ht;Ht=null;let G=w.stopReason,Oe=(Ae=w.result)==null?void 0:Ae.response;if(J)G&&(J.stopReason=G),Oe!=null?ft(J,Oe):J.streaming!==!1&&(ce.delete(J.id),Re.delete(J.id),J.streaming=!1,g(J));else{let ot=Oe!=null&&Oe!=="";if(ot||G){let dt=te();G&&(dt.stopReason=G),ot?fe(dt,Oe):(dt.streaming=!1,g(dt))}}continue}}else if(st==="execution_start")et=w.kind==="flow"?"flow":"agent",zt=!0,et==="agent"&&(ue={executionId:w.executionId,agentId:(Ur=w.agentId)!=null?Ur:"virtual",agentName:(Qn=w.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=w.maxTurns)!=null?_t:1,startedAt:ke(w.startedAt)});else if(st==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let z=y;z&&(z.streaming=!1,g(z),An.set(V-1,z),y=null)}Ce=V}xe=typeof w.id=="string"?w.id:null,v=null}else if(st==="tool_input_delta"){let V=(Yn=w.toolCallId)!=null?Yn:L.lastId;if(V){let z=q.get(V);z!=null&&z.toolCall&&(z.toolCall.chunks=(qr=z.toolCall.chunks)!=null?qr:[],z.toolCall.chunks.push((ta=w.delta)!=null?ta:""),g(z))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=w.stopReason,z=y!=null?y:v;if(V&&z!==null){let J=w.id;(!J||((bs=z.agentMetadata)==null?void 0:bs.turnId)===J)&&(z.stopReason=V,g(z))}xe===w.id&&(xe=null)}else if(st==="media_start"){let V=String(w.id);Te.set(V,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Te.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(st==="media_complete"){let V=String(w.id),z=Te.get(V);Te.delete(V);let J=(zo=(na=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?na:z==null?void 0:z.mediaType)!=null?zo:"application/octet-stream",G=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:z&&z.parts.length>0?z.parts.join(""):void 0,ot=null;if(G)ot={type:"media",data:G,mediaType:J};else if(Oe){let Mn=J.toLowerCase();ot={type:Mn==="image"||Mn.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:J}}let dt=(Er=w.toolCallId)!=null?Er:z==null?void 0:z.toolCallId,fl=ot?[ot]:[],yo=[];for(let Mn of fl){if(!Mn||typeof Mn!="object")continue;let un=Mn,Kr=typeof un.type=="string"?un.type:void 0,Rr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",an=null,kn="";if(Kr==="media"){let fn=typeof un.data=="string"?un.data:void 0;if(!fn)continue;kn=Rr.length>0?Rr:"application/octet-stream",an=`data:${kn};base64,${fn}`}else if(Kr==="image-url"){let fn=typeof un.url=="string"?un.url:void 0;if(!fn)continue;kn=Rr,an=fn}else if(Kr==="file-url"){let fn=typeof un.url=="string"?un.url:void 0;if(!fn)continue;kn=Rr,an=fn}else continue;if(an)if(Kr==="image-url"||kn.startsWith("image/"))yo.push({type:"image",image:an,...kn.includes("/")?{mimeType:kn}:{}});else if(kn.startsWith("audio/"))yo.push({type:"audio",audio:an,mimeType:kn});else if(kn.startsWith("video/"))yo.push({type:"video",video:an,mimeType:kn});else{let fn=kn||"application/octet-stream";yo.push({type:"file",data:an,mimeType:fn,filename:rb(fn)})}}if(yo.length>0){let Mn=p(),un=dt,Rr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${Mn}`:String(Mn)}`,role:"assistant",content:"",contentParts:yo,createdAt:new Date().toISOString(),streaming:!1,sequence:Mn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Rr);let an=y;an&&(an.streaming=!1,g(an)),y=null,S.current=null}}else if(st==="execution_complete"){let V=(go=w.kind)!=null?go:et;V==="agent"&&ue&&(ue.status=w.success?"complete":"error",ue.completedAt=ke(w.completedAt),ue.stopReason=w.stopReason);let z=y;z&&(V==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,g(z)),y=null),P=null,H="",Ht=null,n({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof w.error=="string"?w.error:(on=(ct=w.error)==null?void 0:ct.message)!=null?on:"Execution error";n({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(sn=w.approvalId)!=null?sn:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(Mr=ue==null?void 0:ue.agentId)!=null?Mr:"virtual",executionId:(zr=(ra=w.executionId)!=null?ra:ue==null?void 0:ue.executionId)!=null?zr:"",toolName:(Vo=w.toolName)!=null?Vo:"",toolType:w.toolType,description:($=w.description)!=null?$:`Execute ${(kr=w.toolName)!=null?kr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="step_await"&&w.awaitReason==="approval_required"){let V=(xs=w.approvalId)!=null?xs:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(Zn=ue==null?void 0:ue.agentId)!=null?Zn:"virtual",executionId:(Vr=(Lr=w.executionId)!=null?Lr:ue==null?void 0:ue.executionId)!=null?Vr:"",toolName:(Pr=w.toolName)!=null?Pr:"",toolType:w.toolType,description:(vs=w.description)!=null?vs:`Execute ${(pr=w.toolName)!=null?pr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="approval_complete"){let V=w.approvalId;if(V){let J={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(Ga=w.decision)!=null?Ga:"approved",agentId:(xn=ue==null?void 0:ue.agentId)!=null?xn:"virtual",executionId:(ur=(Tn=w.executionId)!=null?Tn:ue==null?void 0:ue.executionId)!=null?ur:"",toolName:(En=w.toolName)!=null?En:"",description:(Ko=w.description)!=null?Ko:"",resolvedAt:Date.now()}};g(J)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=w.artifactType,z=String(w.id),J=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:z,artifactType:V,title:J,component:typeof w.component=="string"?w.component:void 0}),ye.set(z,{markdown:"",title:J}),!ie.has(z)){ie.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:J,artifactType:V,status:"streaming"}})};ae.set(z,G),g(G)}}else if(st==="artifact_delta"){let V=String(w.id),z=typeof w.delta=="string"?w.delta:String((mr=w.delta)!=null?mr:"");n({type:"artifact_delta",id:V,artDelta:z});let J=ye.get(V);J&&(J.markdown+=z)}else if(st==="artifact_update"){let V=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:V,component:typeof w.component=="string"?w.component:void 0})}else if(st==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let z=ae.get(V);if(z){z.streaming=!1;try{let J=JSON.parse((vn=z.rawContent)!=null?vn:"{}");if(J.props){J.props.status="complete";let G=ye.get(V);G!=null&&G.markdown&&(J.props.markdown=G.markdown)}z.rawContent=JSON.stringify(J)}catch{}ye.delete(V),g(z),ae.delete(V)}}}else if(st==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let z=String((Ir=V.id)!=null?Ir:`msg-${p()}`),J=V.role,Oe={id:z,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:p()};if(g(Oe),Oe.rawContent)try{let ot=JSON.parse(Oe.rawContent),dt=(ws=ot==null?void 0:ot.props)==null?void 0:ws.artifactId;typeof dt=="string"&&ie.add(dt)}catch{}y=null,S.current=null,ce.delete(z),Re.delete(z)}else if(st==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((Go=w.error)==null?void 0:Go.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let z=y;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(st==="dispatch_error"){let z=(Cs=w.message)!=null?Cs:w.error;z!=null&&z!==""&&(V=new Error(String(z)))}else{let z=w.error;typeof z=="string"&&z!==""?V=new Error(z):z!=null&&typeof z=="object"&&Reflect.has(z,"message")&&(V=new Error(String((fo=z.message)!=null?fo:z)))}if(V){n({type:"error",error:V});let z=y;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:M,value:me}=await s.read();if(M)break;i+=a.decode(me,{stream:!0});let Ee=i.split(`
12
12
 
13
- `);i=(vr=Ee.pop())!=null?vr:"";for(let Le of Ee){let Be=Le.split(`
14
- `),rt="message",Ye="",yt=null;for(let de of Be)de.startsWith("event:")?rt=de.replace("event:","").trim():de.startsWith("data:")?Ye+=de.replace("data:","").trim():de.startsWith("id:")&&(yt=de.slice(3).trim());let ge=()=>{yt!==null&&yt!==""&&n({type:"cursor",id:yt})};if(!Ye){ge();continue}let D;try{D=JSON.parse(Ye)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let ve=rt!=="message"?rt:(wr=D.type)!=null?wr:"message";if((qe=this.onSSEEvent)==null||qe.call(this,ve,D),this.parseSSEEvent){T.current=b;let de=await this.handleCustomSSEEvent(D,n,T,g,p,E);if(T.current&&T.current!==b&&(b=T.current),de){ge();continue}}lt.push({payloadType:ve,payload:D}),Ke(),ge()}}Ke()}};function cg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Lo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var gi="[Image]";function dg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function pg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ug(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function mg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ca(e){return{type:"text",text:e}}function gg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function fg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function hg(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 yg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zy=["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"],Yr=[...yg,...zy];function Vy(e){return yg.includes(e)||e.startsWith("image/")}function fi(e){return Vy(e.type)}async function bg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;fi(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function xg(e,t=Yr,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 Ky(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function vg(e,t){let n=Ky(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Ol();var wg=16e3,Gy=24e3,Jy=4096,Xy=1380533830;function Qy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Xy?new Uint8Array(e,44):new Uint8Array(e)}function Yy(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Aa=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:wg,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:wg});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ds(Gy);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${Yy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,b=new WebSocket(g,["runtype.bearer",n]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,b,o))},b.onmessage=v=>this.handleMessage(v,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let T=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Jy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Qy(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var as=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Po(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Aa(e.runtype);case"browser":if(!as.isSupported())throw new Error("Browser speech recognition not supported");return new as(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 hi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Po({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Po({type:"runtype",runtype:e.runtype});if(as.isSupported())return Po({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Sa(e){try{return hi(e),!0}catch{return!1}}function Ns(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Io=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ns(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var is=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Fl(e){if(!e)return"";let t=Zy(e);return Cg(t!==null?t:e)}function Zy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Cg(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=(xr=Ee.pop())!=null?xr:"";for(let Le of Ee){let Be=Le.split(`
14
+ `),rt="message",Ye="",yt=null;for(let de of Be)de.startsWith("event:")?rt=de.replace("event:","").trim():de.startsWith("data:")?Ye+=de.replace("data:","").trim():de.startsWith("id:")&&(yt=de.slice(3).trim());let ge=()=>{yt!==null&&yt!==""&&n({type:"cursor",id:yt})};if(!Ye){ge();continue}let D;try{D=JSON.parse(Ye)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let ve=rt!=="message"?rt:(vr=D.type)!=null?vr:"message";if((qe=this.onSSEEvent)==null||qe.call(this,ve,D),this.parseSSEEvent){S.current=y;let de=await this.handleCustomSSEEvent(D,n,S,g,p,E);if(S.current&&S.current!==y&&(y=S.current),de){ge();continue}}lt.push({payloadType:ve,payload:D}),Ke(),ge()}}Ke()}};function wg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Fs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Io(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var xi="[Image]";function Cg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ag(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Sg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Tg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ta(e){return{type:"text",text:e}}function Eg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Mg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function kg(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 Lg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ab=["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"],to=[...Lg,...ab];function ib(e){return Lg.includes(e)||e.startsWith("image/")}function vi(e){return ib(e.type)}async function Pg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;vi(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Ig(e,t=to,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 lb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Rg(e,t){let n=lb(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"}Vl();var Wg=16e3,cb=24e3,db=4096,pb=1380533830;function ub(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===pb?new Uint8Array(e,44):new Uint8Array(e)}function mb(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ea=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Wg,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Wg});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new _s(cb);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${mb(r)}/ws/agents/${encodeURIComponent(t)}/voice`,y=new WebSocket(g,["runtype.bearer",n]);y.binaryType="arraybuffer",this.ws=y,y.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,y,o))},y.onmessage=v=>this.handleMessage(v,o),y.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},y.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let S=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${S}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(db,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=ub(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var ls=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ro(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ea(e.runtype);case"browser":if(!ls.isSupported())throw new Error("Browser speech recognition not supported");return new ls(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 wi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Ro({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ro({type:"runtype",runtype:e.runtype});if(ls.isSupported())return Ro({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ma(e){try{return wi(e),!0}catch{return!1}}function $s(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Wo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):$s(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var cs=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Kl(e){if(!e)return"";let t=gb(e);return Hg(t!==null?t:e)}function gb(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Hg(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 Mg=null;var _l=()=>Mg?Mg():Promise.resolve().then(()=>(Eg(),Tg));var ob=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function sb(e,t){return ob.some(n=>e[n]!==t[n])}function $l(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
16
+ `),t.trim()}var Fg=null;var Gl=()=>Fg?Fg():Promise.resolve().then(()=>(Og(),Ng));var xb=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function vb(e,t){return xb.some(n=>e[n]!==t[n])}function Jl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
17
17
 
18
- _Details: ${n.message}_`:r}var Ta=e=>({isError:!0,content:[{type:"text",text:e}]}),Pg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ig=e=>Ao(e)||e===br,Os=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 is(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ao(f.name)||f.name===br&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(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),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ss(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||_l().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Sa((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Io.isSupported()?new Io({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return _l().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Po(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!sb(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new ss(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?Bs():n==="assistant"?Lo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?Bs():o==="assistant"?Lo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Bs(),s=Lo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||gi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let T=$l(b,this.config.errorMessage);if(T){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Lo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=$l(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let T=null;if(v instanceof Response){if(!v.ok){let E=await v.json().catch(()=>null);throw new Error((f=E==null?void 0:E.error)!=null?f:`Approval request failed: ${v.status}`)}T=v.body}else v instanceof ReadableStream&&(T=v);T?await this.connectStream(T,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let T=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,T,E,P,I,M,L;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,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=(v=t.toolCall)==null?void 0:v.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let U=typeof((T=R[0])==null?void 0:T.question)=="string"?R[0].question:"";U&&(a={[U]:n})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(P=t.toolCall)==null?void 0:P.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,U])=>`${R}: ${Array.isArray(U)?U.join(", "):U}`).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!=null?a:{};c.forEach((R,U)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let W=C[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((I=R==null?void 0:R.error)!=null?I:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(L=(M=this.callbacks).onError)==null||L.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==br)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=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:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var L,C,R,U,j,W,O;let g=(L=f.toolCall)==null?void 0:L.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let T=this.markWebMcpToolRunning(f),E=(U=(R=f.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?U:g;if(g===br)return{dedupeKey:v,resumeKey:E,output:Rl(),toolMessage:f,startedAt:T,completedAt:Date.now()};let P=new AbortController;this.webMcpResolveControllers.add(P),o.push(P);let I=this.client.executeWebMcpToolCall(g,(j=f.toolCall)==null?void 0:j.args,P.signal),M;if(!I)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await I}catch(F){let ee=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return ee||(O=(W=this.callbacks).onError)==null||O.call(W,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(f,Ta(ee?"Aborted by cancel()":Pg(F)),T),this.webMcpInflightKeys.delete(v),null}return P.signal.aborted?(this.markWebMcpToolComplete(f,Ta("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:E,output:M,toolMessage:f,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===br?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,Ta("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,T,E,P,I,M,L,C,R,U,j;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(T=t.toolCall)==null?void 0:T.id;if(!n){(P=(E=this.callbacks).onError)==null||P.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let W=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(W)||this.webMcpResolvedKeys.has(W))return;this.webMcpInflightKeys.add(W);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(W)}catch(O){(M=(I=this.callbacks).onError)==null||M.call(I,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(W)}return}let s=`${n}:${o}`;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:d}=i;this.setStreaming(!0);let c=r===br,p=(L=t.toolCall)==null?void 0:L.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let W;if(c?W=Rl():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ta("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;f="resume",await this.resumeWithToolOutput(n,O,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(W){let O=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));(f==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,Ta(O||d.aborted?"Aborted by cancel()":Pg(W)),a),O||(j=(U=this.callbacks).onError)==null||j.call(U,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.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){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Lg(),kg)).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,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>$l(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Lo(),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(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,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(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,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!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Fl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ns(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=Fl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,T,E,P,I,M,L,C,R,U;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,W=n.approval;a.approval={...j,...W,executionId:W.executionId||j.executionId,toolName:W.toolName||j.toolName,description:W.description||j.description,toolType:(g=W.toolType)!=null?g:j.toolType,reason:(b=W.reason)!=null?b:j.reason,parameters:(v=W.parameters)!=null?v:j.parameters}}let i=(T=n.toolCall)==null?void 0:T.name,d=(E=n.agentMetadata)==null?void 0:E.executionId,c=(P=n.toolCall)==null?void 0:P.id;if(i&&Ig(i)&&d&&c&&((I=n.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let j=`${d}:${c}`,W=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),F=(M=o.toolCall)==null?void 0:M.name,ee=((L=o.agentMetadata)==null?void 0:L.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&F!==void 0&&Ig(F)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||O||ee)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var A=require("lucide"),ab={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},he=(e,t=24,n="currentColor",r=2)=>{let o=ab[e];return o?ib(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ib(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var xi={allowedTypes:Yr,maxFileSize:10*1024*1024,maxFiles:4};function lb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cb(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 ls=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:xi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:xi.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:xi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:xi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=xg(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await bg(c),f=fi(c)?URL.createObjectURL(c):null,g={id:lb(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=fi(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=cb(t.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=vg(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Rg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ea(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Rg(s)&&Rg(o)?n[r]=Ea(s,o):n[r]=o}return n}var zn="min(440px, calc(100vw - 24px))",vi="440px",db={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:zn,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)"},Bt={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:db,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Wg(e,t){if(!(!e&&!t))return e?t?Ea(e,t):e:t}function wi(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,T,E,P,I,M,L;return e?{...Bt,...e,theme:Wg(Bt.theme,e.theme),darkTheme:Wg(Bt.darkTheme,e.darkTheme),launcher:{...Bt.launcher,...e.launcher,dock:{...(t=Bt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...e.copy},sendButton:{...Bt.sendButton,...e.sendButton},statusIndicator:{...Bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,ae,ie,ye,je,K,Y,ke,X,ce;let C=(oe=Bt.features)==null?void 0:oe.artifacts,R=(ae=e.features)==null?void 0:ae.artifacts,U=(ie=Bt.features)==null?void 0:ie.scrollToBottom,j=(ye=e.features)==null?void 0:ye.scrollToBottom,W=(je=Bt.features)==null?void 0:je.scrollBehavior,O=(K=e.features)==null?void 0:K.scrollBehavior,F=(Y=Bt.features)==null?void 0:Y.streamAnimation,ee=(ke=e.features)==null?void 0:ke.streamAnimation,Me=(X=Bt.features)==null?void 0:X.askUserQuestion,pe=(ce=e.features)==null?void 0:ce.askUserQuestion,te=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},Pe=U===void 0&&j===void 0?void 0:{...U,...j},Ie=W===void 0&&O===void 0?void 0:{...W,...O},re=F===void 0&&ee===void 0?void 0:{...F,...ee},Se=Me===void 0&&pe===void 0?void 0:{...Me,...pe,styles:{...Me==null?void 0:Me.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...e.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...te!==void 0?{artifacts:te}:{},...re!==void 0?{streamAnimation:re}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Bt.layout,...e.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Bt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(I=e.layout)==null?void 0:I.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(M=Bt.markdown)==null?void 0:M.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var jl={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"}},Ul={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"}},ql={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:zn,maxWidth:vi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Fs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Fs(e,r):r}function Ci(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Fs(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.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 zl(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 Hg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Hg(s,o):n[r]=o}return n}function pb(e,t){return t?Hg(e,t):e}function _s(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,T;let n={palette:jl,semantic:Ul,components:ql},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:pb(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=zl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(P=>P.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function Ai(e){var v,T,E,P,I,M,L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie,ye,je,K,Y,ke,X,ce,Re,be,Ge,ft,Ht,nt,fe,Q,lt,Ke,Te,Ce,et,zt,xe,ue,wn,At,hn,vr,wr,qe,k,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,tn,Cr,Fr,ar,ir,no,Vt,lr,_r,Bn,Ln,Dn,cr,Ar,ro,Gn,oo,St,Sr,Tr,$r,dr,bt,Fo,Er,_o,Pn,fs,so,jr,ao,io,$o,jo,lo,wt,Nn,On,Cn,Tt,Jn,Xn,Fn,co;let t=Ci(e),n={};for(let[Ae,Ur]of Object.entries(t)){let Qn=Ae.replace(/\./g,"-");n[`--persona-${Qn}`]=Ur.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(T=n["--persona-semantic-colors-secondary"])!=null?T:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(E=n["--persona-semantic-colors-accent"])!=null?E:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(P=n["--persona-semantic-colors-surface"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(I=n["--persona-semantic-colors-background"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(L=n["--persona-semantic-colors-text"])!=null?L:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(U=n["--persona-semantic-colors-border"])!=null?U:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(F=n["--persona-components-voice-processing-icon"])!=null?F:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ee=n["--persona-components-voice-speaking-icon"])!=null?ee:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Me=n["--persona-components-approval-requested-background"])!=null?Me:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(te=n["--persona-components-approval-requested-text"])!=null?te:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Pe=n["--persona-components-approval-requested-shadow"])!=null?Pe:"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"]=(Ie=n["--persona-components-approval-approve-background"])!=null?Ie:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(re=n["--persona-components-approval-deny-background"])!=null?re:n["--persona-container"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ae=n["--persona-semantic-typography-fontFamily"])!=null?ae:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ie=n["--persona-semantic-typography-fontSize"])!=null?ie:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(je=n["--persona-semantic-typography-lineHeight"])!=null?je:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(Y=n["--persona-palette-radius-md"])!=null?Y:"0.375rem",n["--persona-radius-lg"]=(ke=n["--persona-palette-radius-lg"])!=null?ke:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(ce=n["--persona-palette-radius-full"])!=null?ce:"9999px",n["--persona-launcher-radius"]=(be=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?be:"9999px",n["--persona-launcher-bg"]=(Ge=n["--persona-components-launcher-background"])!=null?Ge:n["--persona-primary"],n["--persona-launcher-fg"]=(ft=n["--persona-components-launcher-foreground"])!=null?ft:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ht=n["--persona-components-launcher-border"])!=null?Ht:n["--persona-border"],n["--persona-button-primary-bg"]=(nt=n["--persona-components-button-primary-background"])!=null?nt:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=(lt=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?lt:"9999px",n["--persona-panel-radius"]=(Te=(Ke=n["--persona-components-panel-borderRadius"])!=null?Ke:n["--persona-radius-xl"])!=null?Te:"0.75rem",n["--persona-panel-border"]=(Ce=n["--persona-components-panel-border"])!=null?Ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(zt=(et=n["--persona-components-panel-shadow"])!=null?et:n["--persona-palette-shadows-xl"])!=null?zt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(xe=n["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(wn=(ue=n["--persona-components-input-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?wn:"0.5rem",n["--persona-message-user-radius"]=(hn=(At=n["--persona-components-message-user-borderRadius"])!=null?At:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-assistant-radius"]=(wr=(vr=n["--persona-components-message-assistant-borderRadius"])!=null?vr:n["--persona-radius-lg"])!=null?wr:"0.5rem",n["--persona-header-bg"]=(qe=n["--persona-components-header-background"])!=null?qe:n["--persona-surface"],n["--persona-header-border"]=(k=n["--persona-components-header-border"])!=null?k:n["--persona-divider"],n["--persona-header-icon-bg"]=(me=n["--persona-components-header-iconBackground"])!=null?me:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ee=n["--persona-components-header-iconForeground"])!=null?Ee:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Le=n["--persona-components-header-titleForeground"])!=null?Le:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Be=n["--persona-components-header-subtitleForeground"])!=null?Be:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(rt=n["--persona-components-header-actionIconForeground"])!=null?rt:n["--persona-muted"];let r=(Ye=e.components)==null?void 0:Ye.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=e.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(ge=n["--persona-components-introCard-background"])!=null?ge:n["--persona-surface"],n["--persona-intro-card-radius"]=(D=n["--persona-components-introCard-borderRadius"])!=null?D:"1rem",n["--persona-intro-card-padding"]=(ve=n["--persona-components-introCard-padding"])!=null?ve:"1.5rem",n["--persona-intro-card-shadow"]=(ht=(de=o==null?void 0:o.shadow)!=null?de:n["--persona-components-introCard-shadow"])!=null?ht:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Xe=n["--persona-components-input-background"])!=null?Xe:n["--persona-surface"],n["--persona-input-placeholder"]=(Pt=n["--persona-components-input-placeholder"])!=null?Pt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(kt=n["--persona-components-message-user-background"])!=null?kt:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Wt=n["--persona-components-message-user-shadow"])!=null?Wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qt=n["--persona-components-message-assistant-background"])!=null?Qt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(tn=n["--persona-components-message-assistant-border"])!=null?tn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Cr=n["--persona-components-message-assistant-shadow"])!=null?Cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(ar=(Fr=n["--persona-components-scrollToBottom-background"])!=null?Fr:n["--persona-button-primary-bg"])!=null?ar:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(no=(ir=n["--persona-components-scrollToBottom-foreground"])!=null?ir:n["--persona-button-primary-fg"])!=null?no:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Vt=n["--persona-components-scrollToBottom-border"])!=null?Vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(lr=n["--persona-components-scrollToBottom-size"])!=null?lr:"40px",n["--persona-scroll-to-bottom-radius"]=(Ln=(Bn=(_r=n["--persona-components-scrollToBottom-borderRadius"])!=null?_r:n["--persona-button-radius"])!=null?Bn:n["--persona-radius-full"])!=null?Ln:"9999px",n["--persona-scroll-to-bottom-shadow"]=(cr=(Dn=n["--persona-components-scrollToBottom-shadow"])!=null?Dn:n["--persona-palette-shadows-sm"])!=null?cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Ar=n["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(ro=n["--persona-components-scrollToBottom-gap"])!=null?ro:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(oo=(Gn=n["--persona-components-scrollToBottom-fontSize"])!=null?Gn:n["--persona-palette-typography-fontSize-sm"])!=null?oo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(St=n["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",n["--persona-tool-bubble-shadow"]=(Sr=n["--persona-components-toolBubble-shadow"])!=null?Sr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Tr=n["--persona-components-reasoningBubble-shadow"])!=null?Tr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($r=n["--persona-components-composer-shadow"])!=null?$r:"none",n["--persona-md-inline-code-bg"]=(dr=n["--persona-components-markdown-inlineCode-background"])!=null?dr:n["--persona-container"],n["--persona-md-inline-code-color"]=(bt=n["--persona-components-markdown-inlineCode-foreground"])!=null?bt:n["--persona-text"],n["--persona-md-link-color"]=(Er=(Fo=n["--persona-components-markdown-link-foreground"])!=null?Fo:n["--persona-accent"])!=null?Er:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(_o=n["--persona-components-markdown-codeBlock-background"])!=null?_o:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Pn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Pn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(fs=n["--persona-components-markdown-codeBlock-textColor"])!=null?fs:"inherit",n["--persona-md-table-header-bg"]=(so=n["--persona-components-markdown-table-headerBackground"])!=null?so:n["--persona-container"],n["--persona-md-table-border-color"]=(jr=n["--persona-components-markdown-table-borderColor"])!=null?jr:n["--persona-border"],n["--persona-md-hr-color"]=(ao=n["--persona-components-markdown-hr-color"])!=null?ao:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(io=n["--persona-components-markdown-blockquote-borderColor"])!=null?io:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=($o=n["--persona-components-markdown-blockquote-background"])!=null?$o:"transparent",n["--persona-md-blockquote-text-color"]=(jo=n["--persona-components-markdown-blockquote-textColor"])!=null?jo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(lo=n["--persona-components-collapsibleWidget-container"])!=null?lo:n["--persona-surface"],n["--cw-surface"]=(wt=n["--persona-components-collapsibleWidget-surface"])!=null?wt:n["--persona-surface"],n["--cw-border"]=(Nn=n["--persona-components-collapsibleWidget-border"])!=null?Nn:n["--persona-border"],n["--persona-message-border"]=(On=n["--persona-components-message-border"])!=null?On:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ae=b.toolbar;Ae.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ae.iconHoverColor),Ae.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ae.iconHoverBackground),Ae.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ae.iconPadding),Ae.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ae.iconBorderRadius),Ae.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ae.iconBorder),Ae.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ae.toggleGroupGap),Ae.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ae.toggleBorderRadius),Ae.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ae.copyBackground),Ae.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ae.copyBorder),Ae.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ae.copyColor),Ae.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ae.copyBorderRadius),Ae.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ae.copyPadding),Ae.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ae.copyMenuBackground,n["--persona-dropdown-bg"]=(Cn=n["--persona-dropdown-bg"])!=null?Cn:Ae.copyMenuBackground),Ae.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ae.copyMenuBorder,n["--persona-dropdown-border"]=(Tt=n["--persona-dropdown-border"])!=null?Tt:Ae.copyMenuBorder),Ae.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ae.copyMenuShadow,n["--persona-dropdown-shadow"]=(Jn=n["--persona-dropdown-shadow"])!=null?Jn:Ae.copyMenuShadow),Ae.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ae.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Xn=n["--persona-dropdown-radius"])!=null?Xn:Ae.copyMenuBorderRadius),Ae.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ae.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Fn=n["--persona-dropdown-item-hover-bg"])!=null?Fn:Ae.copyMenuItemHoverBackground),Ae.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ae.iconBackground),Ae.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ae.toolbarBorder)}if(b!=null&&b.tab){let Ae=b.tab;Ae.background&&(n["--persona-artifact-tab-bg"]=Ae.background),Ae.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ae.activeBackground),Ae.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ae.activeBorder),Ae.borderRadius&&(n["--persona-artifact-tab-radius"]=Ae.borderRadius),Ae.textColor&&(n["--persona-artifact-tab-color"]=Ae.textColor),Ae.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ae.hoverBackground),Ae.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ae.listBackground),Ae.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ae.listBorderColor),Ae.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ae.listPadding)}if(b!=null&&b.pane){let Ae=b.pane;if(Ae.toolbarBackground){let Ur=(co=Fs(e,Ae.toolbarBackground))!=null?co:Ae.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ur}}return n}var Bg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var ub={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Dg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ma=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},mb=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ma()},Vl=e=>mb(e),gb=e=>_s(e),fb=e=>{var n;let t=_s(void 0,{validate:!1});return _s({...e,palette:{...t.palette,colors:{...ub.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},$s=e=>{let t=Vl(e),n=Dg(e==null?void 0:e.theme),r=Dg(e==null?void 0:e.darkTheme);return t==="dark"?fb(Ea(n!=null?n:{},r!=null?r:{})):gb(n)},hb=e=>Ai(e),Ro=(e,t)=>{let n=$s(t),r=hb(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},Si=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ma())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ma());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var Ng=require("idiomorph"),Ti=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ng.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Ei={index:-1,draft:""};function Fg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}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:{...Ei}}}function _g(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,T,E,P,I,M,L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(T=(v=e.toolCall)==null?void 0:v.name)!=null?T:"",(I=(P=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:P.length)!=null?I:0,(R=(C=(L=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((U=e.toolCall)==null?void 0:U.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(F=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?F:0,(te=(pe=(Me=(ee=e.reasoning)==null?void 0:ee.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?te:0,(Se=(re=(Ie=(Pe=e.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:re.slice(-32))!=null?Se:"",(ae=(oe=e.contentParts)==null?void 0:oe.length)!=null?ae:0,(ie=e.stopReason)!=null?ie:"",t].join("\0")}function $g(){return new Map}function jg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Ug(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function qg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Mi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Nr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,t){return Nr(e)-e.scrollTop<=t}function ki(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Li(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function zg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Vg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Kg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var rn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},vn=1e5,Ho=vn+1;var ka={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yb=["pre","code","a","script","style"],Pi=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ka.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ka.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ka.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ka.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ka.buffer}},Jg=[{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"}],La=new Map;for(let e of Jg)La.set(e.name,e);var Xg=e=>{La.set(e.name,e)},Qg=e=>{Jg.some(t=>t.name===e)||La.delete(e)},Yg=()=>Array.from(La.keys()),js=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=La.get(e))!=null?r:null},Ii=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);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(`
19
- `);return s<0?"":e.slice(0,s)}return e},bb=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},xb=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},Kl=/\s/,vb=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},wb=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Kl.test(s[i])){let c=i;for(;c<s.length&&Kl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Kl.test(s[p]);)c.appendChild(bb(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},Cb=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(xb(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},Pa=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:yb).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)vb(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?wb:Cb;for(let g of i)p(g,n,c);return o.innerHTML},Ri=(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},Ia=(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},Gg=new WeakMap,Ab=(e,t)=>{var s;if(!e.styles)return;let n=Gg.get(t);if(n||(n=new Set,Gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},Gl=new WeakMap,Sb=(e,t)=>{if(!e.onAttach)return;let n=Gl.get(t);if(n||(n=new Map,Gl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Zg=e=>{let t=Gl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Wi=(e,t)=>{Ab(e,t),Sb(e,t)};function Jl(e,t=vn){let n=e.style.position,r=e.style.zIndex,o=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=r,e.style.isolation=o}}var Ra=0,Bo=null;function Xl(e=document){var n;if(Ra++,Ra===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Bo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Ra=Math.max(0,Ra-1),Ra===0&&Bo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Bo.originalOverflow,o.style.position=Bo.originalPosition,o.style.top=Bo.originalTop,o.style.width=Bo.originalWidth,s.scrollTo(0,Bo.scrollY),Bo=null}}}var Wa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},on=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Do=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Vn=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Wa.side,width:(o=t==null?void 0:t.width)!=null?o:Wa.width,animate:(s=t==null?void 0:t.animate)!=null?s:Wa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Wa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Wa.maxHeight}};var xr={"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 Tb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Hi=(e,t={})=>{var T,E,P,I,M,L;let{showClose:n=!0,wrapperClassName:r=Tb,buttonSize:o,iconSize:s="28px"}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=y("div",r),c=(P=a.closeButtonTooltipText)!=null?P:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0,u=(M=a.closeButtonIconName)!=null?M:"x",f=(L=a.closeButtonIconText)!=null?L:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Mt("button",{className:ma("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||kn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=he(u,s,"currentColor",1);if(v?(v.style.display="block",b.appendChild(v)):b.textContent=f,d.appendChild(b),p&&c){let C=null,R=()=>{if(C)return;let j=b.ownerDocument,W=j.body;if(!W)return;C=Dr(j,"div","persona-clear-chat-tooltip"),C.textContent=c;let O=Dr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let F=b.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Ho),C.style.left=`${F.left+F.width/2}px`,C.style.top=`${F.top-8}px`,C.style.transform="translate(-50%, -100%)",W.appendChild(C)},U=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",U),b.addEventListener("focus",R),b.addEventListener("blur",U),d._cleanupTooltip=()=>{U(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",U),b.removeEventListener("focus",R),b.removeEventListener("blur",U)}}return{button:b,wrapper:d}},Eb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Bi=(e,t={})=>{var C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie;let{wrapperClassName:n=Eb,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(U=r!=null?r:a.size)!=null?U:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",c=(W=a.iconColor)!=null?W:"",p=(O=a.backgroundColor)!=null?O:"",u=(F=a.borderWidth)!=null?F:"",f=(ee=a.borderColor)!=null?ee:"",g=(Me=a.borderRadius)!=null?Me:"",b=(pe=a.paddingX)!=null?pe:"",v=(te=a.paddingY)!=null?te:"",T=(Pe=a.tooltipText)!=null?Pe:"Clear chat",E=(Ie=a.showTooltip)!=null?Ie:!0,P=y("div",n),I=!!(u||f),M=Mt("button",{className:ma("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!I&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:c||kn.actionIconColor,backgroundColor:p||void 0,border:I?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),L=he(d,o,"currentColor",1);if(L&&(L.style.display="block",M.appendChild(L)),P.appendChild(M),E&&T){let re=null,Se=()=>{if(re)return;let ae=M.ownerDocument,ie=ae.body;if(!ie)return;re=Dr(ae,"div","persona-clear-chat-tooltip"),re.textContent=T;let ye=Dr(ae,"div");ye.className="persona-clear-chat-tooltip-arrow",re.appendChild(ye);let je=M.getBoundingClientRect();re.style.position="fixed",re.style.zIndex=String(Ho),re.style.left=`${je.left+je.width/2}px`,re.style.top=`${je.top-8}px`,re.style.transform="translate(-50%, -100%)",ie.appendChild(re)},oe=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};P.addEventListener("mouseenter",Se),P.addEventListener("mouseleave",oe),M.addEventListener("focus",Se),M.addEventListener("blur",oe),P._cleanupTooltip=()=>{oe(),P.removeEventListener("mouseenter",Se),P.removeEventListener("mouseleave",oe),M.removeEventListener("focus",Se),M.removeEventListener("blur",oe)}}return{button:M,wrapper:P}};var kn={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))"},Zr=e=>{var L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se;let{config:t,showClose:n=!0}=e,r=Mt("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)))"}}),o=(L=t==null?void 0:t.launcher)!=null?L:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(U=o.headerIconHidden)!=null?U:!1,d=o.headerIconName,c=Mt("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(d){let oe=parseFloat(s)||24,ae=he(d,oe*.6,"currentColor",1);ae?c.replaceChildren(ae):c.textContent=(W=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let oe=y("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(ee=(F=t==null?void 0:t.launcher)==null?void 0:F.agentIconText)!=null?ee:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Mt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Me=t==null?void 0:t.launcher)==null?void 0:Me.title)!=null?pe:"Chat Assistant",style:{color:kn.titleColor}}),f=Mt("span",{className:"persona-text-xs",text:(Pe=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:kn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Ie=o.clearChat)!=null?Ie:{},b=(re=g.enabled)!=null?re:!0,v=(Se=g.placement)!=null?Se:"inline",T=null,E=null;if(b){let ae=Bi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=ae.button,E=ae.wrapper,v==="top-right"&&(E.style.right="48px"),v==="inline"&&r.appendChild(E)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:M}=Hi(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:I,closeButtonWrapper:M,clearChatButton:T,clearChatButtonWrapper:E}},cs=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function No(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("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(Ho)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",g.id),g.destructive&&b.setAttribute("data-destructive",""),g.icon){let T=he(g.icon,16,"currentColor",1.5);T&&b.appendChild(T)}let v=document.createElement("span");v.textContent=g.label,b.appendChild(v),b.addEventListener("click",T=>{T.stopPropagation(),p(),n(g.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=b=>{!a.contains(b.target)&&!r.contains(b.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=he(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Ha(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=he(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function Ba(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Di(e){var g,b;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=he(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(b=d.padding)!=null?b:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,T;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(T=d.border)!=null?T:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=No({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Ql=e=>{var r;let t=Zr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.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 Mb(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=he(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=No({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Yl=e=>{var P,I,M,L,C,R,U,j,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(P=t==null?void 0:t.launcher)!=null?P:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Di({label:(I=a.title)!=null?I:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=kn.titleColor,p=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=kn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),Mb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let F=o.onTitleClick;c.addEventListener("click",ee=>{ee.target.closest("button")||F()}),c.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),F())})}let O=o==null?void 0:o.titleRowHover;O&&(c.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",c.style.padding=(U=O.padding)!=null?U:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var F,ee;c.style.backgroundColor=(F=O.background)!=null?F:"",c.style.borderColor=(ee=O.border)!=null?ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(j=a.closeButtonSize)!=null?j:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||kn.actionIconColor;let b=(W=a.closeButtonIconName)!=null?W:"x",v=he(b,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let T=y("div");T.style.display="none";let E=y("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:p,headerSubtitle:E,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ni={default:Ql,minimal:Yl},Zl=e=>{var t;return(t=Ni[e])!=null?t:Ni.default},Us=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),f=y("span"),g=y("button");g.style.display="none";let b=y("div");return b.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Zl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(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 Oi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Fi=e=>{var L,C,R,U,j,W,O,F,ee,Me,pe,te;let t=(L=e==null?void 0:e.sendButton)!=null?L:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(U=t.stopIconName)!=null?U:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(F=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?F:"Send",c=(Me=(ee=e==null?void 0:e.copy)==null?void 0:ee.stopButtonLabel)!=null?Me:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(te=t.size)!=null?te:"40px",f=t.backgroundColor,g=t.textColor,b=y("div","persona-send-button-wrapper"),v=Mt("button",{className:ma("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&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,E=null;if(n){let Pe=parseFloat(u)||24,Ie=(g==null?void 0:g.trim())||"currentColor";o?(T=he(o,Pe,Ie,2),T?v.appendChild(T):v.textContent=r):v.textContent=r,E=he(s,Pe,Ie,2)}else v.textContent=d;let P=null;p&&a&&(P=y("div","persona-send-button-tooltip"),P.textContent=a,b.appendChild(P)),v.setAttribute("aria-label",a),b.appendChild(v);let I="send";return{button:v,wrapper:b,setMode:Pe=>{if(Pe===I)return;I=Pe;let Ie=Pe==="stop"?i:a;if(v.setAttribute("aria-label",Ie),P&&(P.textContent=Ie),n){if(T&&E){let re=Pe==="stop"?E:T;v.replaceChildren(re)}}else v.textContent=Pe==="stop"?c:d}}},_i=e=>{var P,I,M,L,C,R,U,j,W,O,F,ee;let t=(P=e==null?void 0:e.voiceRecognition)!=null?P:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((I=t.provider)==null?void 0:I.type)==="runtype";if(!(r||o))return null;let a=(L=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?L:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,c=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(U=e==null?void 0:e.sendButton)==null?void 0:U.backgroundColor,u=(O=t.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor,f=y("div","persona-send-button-wrapper"),g=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=he(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let T=(F=t.tooltipText)!=null?F:"Start voice recognition";if(((ee=t.showTooltip)!=null?ee:!1)&&T){let Me=y("div","persona-send-button-tooltip");Me.textContent=T,f.appendChild(Me)}return{button:g,wrapper:f}},$i=e=>{var b,v,T,E,P,I,M,L;let t=(b=e==null?void 0:e.attachments)!=null?b:{};if(t.enabled!==!0)return null;let n=(T=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?T:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((E=t.allowedTypes)!=null?E:Yr).join(","),o.multiple=((P=t.maxFiles)!=null?P:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(I=t.buttonIconName)!=null?I:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Mt("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":(M=t.buttonTooltipText)!=null?M:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=he(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let f=(L=t.buttonTooltipText)!=null?L:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},ji=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Ui=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var qs=e=>{var b,v,T,E,P,I;let{config:t}=e,n=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Ui(),o=Mt("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}=Oi(t);a();let i=Fi(t),d=_i(t),c=$i(t),p=ji(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(P=c==null?void 0:c.input)!=null?P:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var ef=()=>{let e=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=he("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},tf=e=>{var b,v,T,E,P,I;let{config:t}=e,n=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ui();r.style.display="none";let o=ji(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Oi(t);s.style.maxHeight="100px",a();let i=Fi(t),d=_i(t),c=$i(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(P=c==null?void 0:c.input)!=null?P:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var nf=e=>{var p,u,f,g,b,v,T,E,P,I,M,L,C,R,U,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=on(e);if(Do(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},F=y("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(b=O.expandedSize)!=null?b:"anchored",F.style.zIndex=String((T=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?T:vn);let ee=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ee.style.width="100%",F.appendChild(ee);let Me=y("div","persona-widget-pill-root");return Me.setAttribute("data-persona-composer-bar",""),Me.dataset.state="collapsed",Me.dataset.expandedSize=(E=O.expandedSize)!=null?E:"anchored",Me.style.zIndex=String((I=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?I:vn),{wrapper:F,panel:ee,pillRoot:Me}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(F),{wrapper:O,panel:F}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ee=(L=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?L:"100%";return O.style.width=ee,F.style.width="100%",O.appendChild(F),{wrapper:O,panel:F}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&xr[o.position]?xr[o.position]:xr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((U=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?U:vn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,c=d!=null?d:zn;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},kb=(e,t)=>{var M,L,C,R,U,j,W,O,F;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Hi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(L=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:L.enabled)!=null?C:!0,a=null,i=null;if(s){let ee=Bi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ee.button,i=ee.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(U=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?U:"Hello \u{1F44B}"}),u=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),f=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),b=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((F=e==null?void 0:e.copy)==null?void 0:F.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let T=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=tf({config:e}),{root:P,textNode:I}=ef();return n.append(d,o,c,T),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:T,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:P,peekTextNode:I}},rf=(e,t=!0)=>{var T,E,P,I,M,L,C,R,U;if(Do(e))return kb(e,t);let n=Mt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(T=e==null?void 0:e.layout)==null?void 0:T.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Us(e,r,{showClose:t}):Zr({config:e,showClose:t}),a=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(I=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=qs({config:e}),b=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;o?cs(n,s,e):(s.header.style.display="none",cs(n,s,e)),n.append(a);let v=Mt("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 b||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var ec=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
+ _Details: ${n.message}_`:r}var ka=e=>({isError:!0,content:[{type:"text",text:e}]}),jg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ug=e=>To(e)||e===yr,js=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 cs(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(To(f.name)||f.name===yr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(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),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new is(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||Gl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ma((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Wo.isSupported()?new Wo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return Gl().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:y})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new y(v,n,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Ro(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!vb(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new is(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?Fs():n==="assistant"?Io():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?Fs():o==="assistant"?Io():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Fs(),s=Io();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||xi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){if(this.status==="resuming"||this.reconnecting)return;let v=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!v){let S=Jl(y,this.config.errorMessage);if(S){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(y instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,y):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Io();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=Jl(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,y;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let S=null;if(v instanceof Response){if(!v.ok){let E=await v.json().catch(()=>null);throw new Error((f=E==null?void 0:E.error)!=null?f:`Approval request failed: ${v.status}`)}S=v.body}else v instanceof ReadableStream&&(S=v);S?await this.connectStream(S,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(y=(g=this.callbacks).onError)==null||y.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,y,v,S,E,P,H,W,I;let r=this.messages.find(T=>T.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(y=(g=this.callbacks).onError)==null||y.call(g,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 T=(v=t.toolCall)==null?void 0:v.args,B=Array.isArray(T==null?void 0:T.questions)?T.questions:[];if(B.length===1){let q=typeof((S=B[0])==null?void 0:S.question)=="string"?B[0].question:"";q&&(a={[q]:n})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(P=t.toolCall)==null?void 0:P.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let T=typeof n=="string"?n:Object.entries(n).map(([B,q])=>`${B}: ${Array.isArray(q)?q.join(", "):q}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let T=a!=null?a:{};c.forEach((B,q)=>{let U=typeof(B==null?void 0:B.question)=="string"?B.question:"";if(!U)return;let L=T[U],F=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${q}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${q}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let T=await this.client.resumeFlow(o,{[s]:n});if(!T.ok){let B=await T.json().catch(()=>null);throw new Error((H=B==null?void 0:B.error)!=null?H:`Resume failed: ${T.status}`)}T.body?await this.connectStream(T.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(T){let B=T instanceof Error&&(T.name==="AbortError"||T.message.includes("aborted")||T.message.includes("abort"));this.setStreaming(!1),this.abortController=null,B||(I=(W=this.callbacks).onError)==null||I.call(W,T instanceof Error?T:new Error(String(T)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==yr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=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:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var I,T,B,q,U,L,F;let g=(I=f.toolCall)==null?void 0:I.name,y=(T=f.toolCall)==null?void 0:T.id;if(!g||!y)return null;let v=`${t}:${y}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let S=this.markWebMcpToolRunning(f),E=(q=(B=f.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?q:g;if(g===yr)return{dedupeKey:v,resumeKey:E,output:_l(),toolMessage:f,startedAt:S,completedAt:Date.now()};let P=new AbortController;this.webMcpResolveControllers.add(P),o.push(P);let H=this.client.executeWebMcpToolCall(g,(U=f.toolCall)==null?void 0:U.args,P.signal),W;if(!H)W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{W=await H}catch(_){let ee=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return ee||(F=(L=this.callbacks).onError)==null||F.call(L,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(f,ka(ee?"Aborted by cancel()":jg(_)),S),this.webMcpInflightKeys.delete(v),null}return P.signal.aborted?(this.markWebMcpToolComplete(f,ka("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:E,output:W,toolMessage:f,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(y=>y!==null),i.length===0)return;let f={};for(let y of i)f[y.resumeKey]=y.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let y=await g.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${g.status}`)}for(let y of i)this.webMcpResolvedKeys.add(y.dedupeKey),this.markWebMcpToolComplete(y.toolMessage,y.output,y.startedAt,y.completedAt,((c=y.toolMessage.toolCall)==null?void 0:c.name)===yr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let y of i)this.markWebMcpToolComplete(y.toolMessage,ka("Aborted by cancel()"),y.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var y,v,S,E,P,H,W,I,T,B,q,U;let n=(y=t.agentMetadata)==null?void 0:y.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(S=t.toolCall)==null?void 0:S.id;if(!n){(P=(E=this.callbacks).onError)==null||P.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let L=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(L)}catch(F){(W=(H=this.callbacks).onError)==null||W.call(H,F instanceof Error?F:new Error(String(F)))}finally{this.webMcpInflightKeys.delete(L)}return}let s=`${n}:${o}`;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:d}=i;this.setStreaming(!0);let c=r===yr,p=(I=t.toolCall)==null?void 0:I.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let L;if(c?L=_l():u?L=await u:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ka("Aborted by cancel()"),a);return}let F=(B=(T=t.agentMetadata)==null?void 0:T.webMcpToolCallId)!=null?B:r;f="resume",await this.resumeWithToolOutput(n,F,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,L,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(L){let F=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(f==="execute"||F||d.aborted)&&this.markWebMcpToolComplete(t,ka(F||d.aborted?"Aborted by cancel()":jg(L)),a),F||(U=(q=this.callbacks).onError)==null||U.call(q,L instanceof Error?L:new Error(String(L)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.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){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>($g(),_g)).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,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>Jl(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Io(),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(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,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(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,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!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Kl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return $s(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=Kl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,y,v,S,E,P,H,W,I,T,B,q;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let U=o.approval,L=n.approval;a.approval={...U,...L,executionId:L.executionId||U.executionId,toolName:L.toolName||U.toolName,description:L.description||U.description,toolType:(g=L.toolType)!=null?g:U.toolType,reason:(y=L.reason)!=null?y:U.reason,parameters:(v=L.parameters)!=null?v:U.parameters}}let i=(S=n.toolCall)==null?void 0:S.name,d=(E=n.agentMetadata)==null?void 0:E.executionId,c=(P=n.toolCall)==null?void 0:P.id;if(i&&Ug(i)&&d&&c&&((H=n.agentMetadata)==null?void 0:H.awaitingLocalTool)===!0){let U=`${d}:${c}`,L=this.webMcpInflightKeys.has(U),F=this.webMcpResolvedKeys.has(U),_=(W=o.toolCall)==null?void 0:W.name,ee=((I=o.agentMetadata)==null?void 0:I.executionId)===d&&((T=o.toolCall)==null?void 0:T.id)===c&&_!==void 0&&Ug(_)&&((B=o.toolCall)==null?void 0:B.status)==="complete";(L||F||ee)&&(a.agentMetadata={...(q=a.agentMetadata)!=null?q:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var A=require("lucide"),wb={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},he=(e,t=24,n="currentColor",r=2)=>{let o=wb[e];return o?Cb(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Cb(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Si={allowedTypes:to,maxFileSize:10*1024*1024,maxFiles:4};function Ab(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Sb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Si.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Si.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Si.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:Si.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Ig(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Pg(c),f=vi(c)?URL.createObjectURL(c):null,g={id:Ab(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=vi(t.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=b("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=Sb(t.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Rg(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function La(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];qg(s)&&qg(o)?n[r]=La(s,o):n[r]=o}return n}var zn="min(440px, calc(100vw - 24px))",Ti="440px",Tb={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:zn,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)"},Bt={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:Tb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function zg(e,t){if(!(!e&&!t))return e?t?La(e,t):e:t}function Ei(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,y,v,S,E,P,H,W,I;return e?{...Bt,...e,theme:zg(Bt.theme,e.theme),darkTheme:zg(Bt.darkTheme,e.darkTheme),launcher:{...Bt.launcher,...e.launcher,dock:{...(t=Bt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...e.copy},sendButton:{...Bt.sendButton,...e.sendButton},statusIndicator:{...Bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,ae,ie,ye,je,K,Y,ke,X,ce;let T=(oe=Bt.features)==null?void 0:oe.artifacts,B=(ae=e.features)==null?void 0:ae.artifacts,q=(ie=Bt.features)==null?void 0:ie.scrollToBottom,U=(ye=e.features)==null?void 0:ye.scrollToBottom,L=(je=Bt.features)==null?void 0:je.scrollBehavior,F=(K=e.features)==null?void 0:K.scrollBehavior,_=(Y=Bt.features)==null?void 0:Y.streamAnimation,ee=(ke=e.features)==null?void 0:ke.streamAnimation,Me=(X=Bt.features)==null?void 0:X.askUserQuestion,pe=(ce=e.features)==null?void 0:ce.askUserQuestion,te=T===void 0&&B===void 0?void 0:{...T,...B,layout:{...T==null?void 0:T.layout,...B==null?void 0:B.layout}},Pe=q===void 0&&U===void 0?void 0:{...q,...U},Ie=L===void 0&&F===void 0?void 0:{...L,...F},re=_===void 0&&ee===void 0?void 0:{..._,...ee},Se=Me===void 0&&pe===void 0?void 0:{...Me,...pe,styles:{...Me==null?void 0:Me.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...e.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...te!==void 0?{artifacts:te}:{},...re!==void 0?{streamAnimation:re}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Bt.layout,...e.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(y=Bt.layout)==null?void 0:y.messages)==null?void 0:v.timestamp,...(E=(S=e.layout)==null?void 0:S.messages)==null?void 0:E.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(W=Bt.markdown)==null?void 0:W.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var Xl={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ql={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"}},Yl={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:zn,maxWidth:Ti,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Us(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Us(e,r):r}function Mi(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Us(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.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 Zl(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 Vg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Vg(s,o):n[r]=o}return n}function Eb(e,t){return t?Vg(e,t):e}function qs(e,t={}){var o,s,a,i,d,c,p,u,f,g,y,v,S;let n={palette:Xl,semantic:Ql,components:Yl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(y=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:y.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:Eb(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Zl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(P=>P.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function ki(e){var v,S,E,P,H,W,I,T,B,q,U,L,F,_,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie,ye,je,K,Y,ke,X,ce,Re,be,Ge,ft,Ht,nt,fe,Q,lt,Ke,Te,Ce,et,zt,xe,ue,An,At,bn,xr,vr,qe,M,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,en,wr,Fr,ar,ir,so,Vt,lr,_r,Bn,In,Dn,cr,Cr,ao,Gn,io,St,Ar,Sr,$r,dr,bt,$o,Tr,jo,Rn,ys,lo,jr,co,po,Uo,qo,uo,wt,Nn,On,Sn,Tt,Jn,Xn,Fn,mo;let t=Mi(e),n={};for(let[Ae,Ur]of Object.entries(t)){let Qn=Ae.replace(/\./g,"-");n[`--persona-${Qn}`]=Ur.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(S=n["--persona-semantic-colors-secondary"])!=null?S:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(E=n["--persona-semantic-colors-accent"])!=null?E:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(P=n["--persona-semantic-colors-surface"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(W=n["--persona-semantic-colors-container"])!=null?W:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(I=n["--persona-semantic-colors-text"])!=null?I:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(T=n["--persona-semantic-colors-text-muted"])!=null?T:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(B=n["--persona-semantic-colors-text-inverse"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(q=n["--persona-semantic-colors-border"])!=null?q:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(U=n["--persona-semantic-colors-divider"])!=null?U:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(L=n["--persona-components-voice-recording-indicator"])!=null?L:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(F=n["--persona-components-voice-recording-background"])!=null?F:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(_=n["--persona-components-voice-processing-icon"])!=null?_:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ee=n["--persona-components-voice-speaking-icon"])!=null?ee:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Me=n["--persona-components-approval-requested-background"])!=null?Me:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(te=n["--persona-components-approval-requested-text"])!=null?te:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Pe=n["--persona-components-approval-requested-shadow"])!=null?Pe:"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"]=(Ie=n["--persona-components-approval-approve-background"])!=null?Ie:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(re=n["--persona-components-approval-deny-background"])!=null?re:n["--persona-container"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ae=n["--persona-semantic-typography-fontFamily"])!=null?ae:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ie=n["--persona-semantic-typography-fontSize"])!=null?ie:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(je=n["--persona-semantic-typography-lineHeight"])!=null?je:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(Y=n["--persona-palette-radius-md"])!=null?Y:"0.375rem",n["--persona-radius-lg"]=(ke=n["--persona-palette-radius-lg"])!=null?ke:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(ce=n["--persona-palette-radius-full"])!=null?ce:"9999px",n["--persona-launcher-radius"]=(be=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?be:"9999px",n["--persona-launcher-bg"]=(Ge=n["--persona-components-launcher-background"])!=null?Ge:n["--persona-primary"],n["--persona-launcher-fg"]=(ft=n["--persona-components-launcher-foreground"])!=null?ft:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ht=n["--persona-components-launcher-border"])!=null?Ht:n["--persona-border"],n["--persona-button-primary-bg"]=(nt=n["--persona-components-button-primary-background"])!=null?nt:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=(lt=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?lt:"9999px",n["--persona-panel-radius"]=(Te=(Ke=n["--persona-components-panel-borderRadius"])!=null?Ke:n["--persona-radius-xl"])!=null?Te:"0.75rem",n["--persona-panel-border"]=(Ce=n["--persona-components-panel-border"])!=null?Ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(zt=(et=n["--persona-components-panel-shadow"])!=null?et:n["--persona-palette-shadows-xl"])!=null?zt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(xe=n["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(An=(ue=n["--persona-components-input-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?An:"0.5rem",n["--persona-message-user-radius"]=(bn=(At=n["--persona-components-message-user-borderRadius"])!=null?At:n["--persona-radius-lg"])!=null?bn:"0.5rem",n["--persona-message-assistant-radius"]=(vr=(xr=n["--persona-components-message-assistant-borderRadius"])!=null?xr:n["--persona-radius-lg"])!=null?vr:"0.5rem",n["--persona-header-bg"]=(qe=n["--persona-components-header-background"])!=null?qe:n["--persona-surface"],n["--persona-header-border"]=(M=n["--persona-components-header-border"])!=null?M:n["--persona-divider"],n["--persona-header-icon-bg"]=(me=n["--persona-components-header-iconBackground"])!=null?me:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ee=n["--persona-components-header-iconForeground"])!=null?Ee:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Le=n["--persona-components-header-titleForeground"])!=null?Le:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Be=n["--persona-components-header-subtitleForeground"])!=null?Be:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(rt=n["--persona-components-header-actionIconForeground"])!=null?rt:n["--persona-muted"];let r=(Ye=e.components)==null?void 0:Ye.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=e.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(ge=n["--persona-components-introCard-background"])!=null?ge:n["--persona-surface"],n["--persona-intro-card-radius"]=(D=n["--persona-components-introCard-borderRadius"])!=null?D:"1rem",n["--persona-intro-card-padding"]=(ve=n["--persona-components-introCard-padding"])!=null?ve:"1.5rem",n["--persona-intro-card-shadow"]=(ht=(de=o==null?void 0:o.shadow)!=null?de:n["--persona-components-introCard-shadow"])!=null?ht:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Xe=n["--persona-components-input-background"])!=null?Xe:n["--persona-surface"],n["--persona-input-placeholder"]=(Pt=n["--persona-components-input-placeholder"])!=null?Pt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(kt=n["--persona-components-message-user-background"])!=null?kt:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Wt=n["--persona-components-message-user-shadow"])!=null?Wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qt=n["--persona-components-message-assistant-background"])!=null?Qt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wr=n["--persona-components-message-assistant-shadow"])!=null?wr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(ar=(Fr=n["--persona-components-scrollToBottom-background"])!=null?Fr:n["--persona-button-primary-bg"])!=null?ar:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(so=(ir=n["--persona-components-scrollToBottom-foreground"])!=null?ir:n["--persona-button-primary-fg"])!=null?so:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Vt=n["--persona-components-scrollToBottom-border"])!=null?Vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(lr=n["--persona-components-scrollToBottom-size"])!=null?lr:"40px",n["--persona-scroll-to-bottom-radius"]=(In=(Bn=(_r=n["--persona-components-scrollToBottom-borderRadius"])!=null?_r:n["--persona-button-radius"])!=null?Bn:n["--persona-radius-full"])!=null?In:"9999px",n["--persona-scroll-to-bottom-shadow"]=(cr=(Dn=n["--persona-components-scrollToBottom-shadow"])!=null?Dn:n["--persona-palette-shadows-sm"])!=null?cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Cr=n["--persona-components-scrollToBottom-padding"])!=null?Cr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(ao=n["--persona-components-scrollToBottom-gap"])!=null?ao:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(io=(Gn=n["--persona-components-scrollToBottom-fontSize"])!=null?Gn:n["--persona-palette-typography-fontSize-sm"])!=null?io:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(St=n["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",n["--persona-tool-bubble-shadow"]=(Ar=n["--persona-components-toolBubble-shadow"])!=null?Ar:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Sr=n["--persona-components-reasoningBubble-shadow"])!=null?Sr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($r=n["--persona-components-composer-shadow"])!=null?$r:"none",n["--persona-md-inline-code-bg"]=(dr=n["--persona-components-markdown-inlineCode-background"])!=null?dr:n["--persona-container"],n["--persona-md-inline-code-color"]=(bt=n["--persona-components-markdown-inlineCode-foreground"])!=null?bt:n["--persona-text"],n["--persona-md-link-color"]=(Tr=($o=n["--persona-components-markdown-link-foreground"])!=null?$o:n["--persona-accent"])!=null?Tr:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(jo=n["--persona-components-markdown-codeBlock-background"])!=null?jo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Rn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Rn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ys=n["--persona-components-markdown-codeBlock-textColor"])!=null?ys:"inherit",n["--persona-md-table-header-bg"]=(lo=n["--persona-components-markdown-table-headerBackground"])!=null?lo:n["--persona-container"],n["--persona-md-table-border-color"]=(jr=n["--persona-components-markdown-table-borderColor"])!=null?jr:n["--persona-border"],n["--persona-md-hr-color"]=(co=n["--persona-components-markdown-hr-color"])!=null?co:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(po=n["--persona-components-markdown-blockquote-borderColor"])!=null?po:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Uo=n["--persona-components-markdown-blockquote-background"])!=null?Uo:"transparent",n["--persona-md-blockquote-text-color"]=(qo=n["--persona-components-markdown-blockquote-textColor"])!=null?qo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(uo=n["--persona-components-collapsibleWidget-container"])!=null?uo:n["--persona-surface"],n["--cw-surface"]=(wt=n["--persona-components-collapsibleWidget-surface"])!=null?wt:n["--persona-surface"],n["--cw-border"]=(Nn=n["--persona-components-collapsibleWidget-border"])!=null?Nn:n["--persona-border"],n["--persona-message-border"]=(On=n["--persona-components-message-border"])!=null?On:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let Ae=y.toolbar;Ae.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ae.iconHoverColor),Ae.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ae.iconHoverBackground),Ae.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ae.iconPadding),Ae.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ae.iconBorderRadius),Ae.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ae.iconBorder),Ae.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ae.toggleGroupGap),Ae.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ae.toggleBorderRadius),Ae.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ae.copyBackground),Ae.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ae.copyBorder),Ae.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ae.copyColor),Ae.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ae.copyBorderRadius),Ae.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ae.copyPadding),Ae.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ae.copyMenuBackground,n["--persona-dropdown-bg"]=(Sn=n["--persona-dropdown-bg"])!=null?Sn:Ae.copyMenuBackground),Ae.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ae.copyMenuBorder,n["--persona-dropdown-border"]=(Tt=n["--persona-dropdown-border"])!=null?Tt:Ae.copyMenuBorder),Ae.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ae.copyMenuShadow,n["--persona-dropdown-shadow"]=(Jn=n["--persona-dropdown-shadow"])!=null?Jn:Ae.copyMenuShadow),Ae.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ae.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Xn=n["--persona-dropdown-radius"])!=null?Xn:Ae.copyMenuBorderRadius),Ae.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ae.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Fn=n["--persona-dropdown-item-hover-bg"])!=null?Fn:Ae.copyMenuItemHoverBackground),Ae.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ae.iconBackground),Ae.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ae.toolbarBorder)}if(y!=null&&y.tab){let Ae=y.tab;Ae.background&&(n["--persona-artifact-tab-bg"]=Ae.background),Ae.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ae.activeBackground),Ae.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ae.activeBorder),Ae.borderRadius&&(n["--persona-artifact-tab-radius"]=Ae.borderRadius),Ae.textColor&&(n["--persona-artifact-tab-color"]=Ae.textColor),Ae.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ae.hoverBackground),Ae.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ae.listBackground),Ae.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ae.listBorderColor),Ae.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ae.listPadding)}if(y!=null&&y.pane){let Ae=y.pane;if(Ae.toolbarBackground){let Ur=(mo=Us(e,Ae.toolbarBackground))!=null?mo:Ae.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ur}}return n}var Kg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Mb={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"}}},Gg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Pa=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},kb=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Pa()},ec=e=>kb(e),Lb=e=>qs(e),Pb=e=>{var n;let t=qs(void 0,{validate:!1});return qs({...e,palette:{...t.palette,colors:{...Mb.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},zs=e=>{let t=ec(e),n=Gg(e==null?void 0:e.theme),r=Gg(e==null?void 0:e.darkTheme);return t==="dark"?Pb(La(n!=null?n:{},r!=null?r:{})):Lb(n)},Ib=e=>ki(e),Ho=(e,t)=>{let n=zs(t),r=Ib(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},Li=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Pa())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Pa());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var Jg=require("idiomorph"),Pi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Jg.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Xg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Ii={index:-1,draft:""};function Qg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}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:{...Ii}}}function Yg(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,y,v,S,E,P,H,W,I,T,B,q,U,L,F,_,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(y=(g=e.toolCall)==null?void 0:g.status)!=null?y:"",(S=(v=e.toolCall)==null?void 0:v.name)!=null?S:"",(H=(P=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:P.length)!=null?H:0,(B=(T=(I=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:T.slice(-32))!=null?B:"",typeof((q=e.toolCall)==null?void 0:q.args)=="string"?e.toolCall.args.length:(U=e.toolCall)!=null&&U.args?JSON.stringify(e.toolCall.args).length:0,(_=(F=(L=e.reasoning)==null?void 0:L.chunks)==null?void 0:F.length)!=null?_:0,(te=(pe=(Me=(ee=e.reasoning)==null?void 0:ee.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?te:0,(Se=(re=(Ie=(Pe=e.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:re.slice(-32))!=null?Se:"",(ae=(oe=e.contentParts)==null?void 0:oe.length)!=null?ae:0,(ie=e.stopReason)!=null?ie:"",t].join("\0")}function Zg(){return new Map}function ef(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function tf(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function nf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ri(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Nr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Bo(e,t){return Nr(e)-e.scrollTop<=t}function Wi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Hi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function rf(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function of(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 sf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Cn=1e5,Do=Cn+1;var Ia={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Rb=["pre","code","a","script","style"],Bi=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ia.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ia.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ia.speed,duration:(o=e==null?void 0:e.duration)!=null?o:Ia.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ia.buffer}},lf=[{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"}],Ra=new Map;for(let e of lf)Ra.set(e.name,e);var cf=e=>{Ra.set(e.name,e)},df=e=>{lf.some(t=>t.name===e)||Ra.delete(e)},pf=()=>Array.from(Ra.keys()),Vs=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Ra.get(e))!=null?r:null},Di=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);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(`
19
+ `);return s<0?"":e.slice(0,s)}return e},Wb=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Hb=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},tc=/\s/,Bb=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Db=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(tc.test(s[i])){let c=i;for(;c<s.length&&tc.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!tc.test(s[p]);)c.appendChild(Wb(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},Nb=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Hb(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},Wa=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Rb).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Bb(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Db:Nb;for(let g of i)p(g,n,c);return o.innerHTML},Ni=(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},Ha=(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},af=new WeakMap,Ob=(e,t)=>{var s;if(!e.styles)return;let n=af.get(t);if(n||(n=new Set,af.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},nc=new WeakMap,Fb=(e,t)=>{if(!e.onAttach)return;let n=nc.get(t);if(n||(n=new Map,nc.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},uf=e=>{let t=nc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Oi=(e,t)=>{Ob(e,t),Fb(e,t)};function rc(e,t=Cn){let n=e.style.position,r=e.style.zIndex,o=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=r,e.style.isolation=o}}var Ba=0,No=null;function oc(e=document){var n;if(Ba++,Ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;No={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Ba=Math.max(0,Ba-1),Ba===0&&No)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=No.originalOverflow,o.style.position=No.originalPosition,o.style.top=No.originalTop,o.style.width=No.originalWidth,s.scrollTo(0,No.scrollY),No=null}}}var Da={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Oo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Vn=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Da.side,width:(o=t==null?void 0:t.width)!=null?o:Da.width,animate:(s=t==null?void 0:t.animate)!=null?s:Da.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Da.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Da.maxHeight}};var br={"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 _b="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Fi=(e,t={})=>{var S,E,P,H,W,I;let{showClose:n=!0,wrapperClassName:r=_b,buttonSize:o,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=b("div",r),c=(P=a.closeButtonTooltipText)!=null?P:"Close chat",p=(H=a.closeButtonShowTooltip)!=null?H:!0,u=(W=a.closeButtonIconName)!=null?W:"x",f=(I=a.closeButtonIconText)!=null?I:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Mt("button",{className:ya("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Pn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=he(u,s,"currentColor",1);if(v?(v.style.display="block",y.appendChild(v)):y.textContent=f,d.appendChild(y),p&&c){let T=null,B=()=>{if(T)return;let U=y.ownerDocument,L=U.body;if(!L)return;T=Dr(U,"div","persona-clear-chat-tooltip"),T.textContent=c;let F=Dr(U,"div");F.className="persona-clear-chat-tooltip-arrow",T.appendChild(F);let _=y.getBoundingClientRect();T.style.position="fixed",T.style.zIndex=String(Do),T.style.left=`${_.left+_.width/2}px`,T.style.top=`${_.top-8}px`,T.style.transform="translate(-50%, -100%)",L.appendChild(T)},q=()=>{T&&T.parentNode&&(T.parentNode.removeChild(T),T=null)};d.addEventListener("mouseenter",B),d.addEventListener("mouseleave",q),y.addEventListener("focus",B),y.addEventListener("blur",q),d._cleanupTooltip=()=>{q(),d.removeEventListener("mouseenter",B),d.removeEventListener("mouseleave",q),y.removeEventListener("focus",B),y.removeEventListener("blur",q)}}return{button:y,wrapper:d}},$b="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",_i=(e,t={})=>{var T,B,q,U,L,F,_,ee,Me,pe,te,Pe,Ie;let{wrapperClassName:n=$b,buttonSize:r,iconSize:o="20px"}=t,a=(B=((T=e==null?void 0:e.launcher)!=null?T:{}).clearChat)!=null?B:{},i=(q=r!=null?r:a.size)!=null?q:"32px",d=(U=a.iconName)!=null?U:"refresh-cw",c=(L=a.iconColor)!=null?L:"",p=(F=a.backgroundColor)!=null?F:"",u=(_=a.borderWidth)!=null?_:"",f=(ee=a.borderColor)!=null?ee:"",g=(Me=a.borderRadius)!=null?Me:"",y=(pe=a.paddingX)!=null?pe:"",v=(te=a.paddingY)!=null?te:"",S=(Pe=a.tooltipText)!=null?Pe:"Clear chat",E=(Ie=a.showTooltip)!=null?Ie:!0,P=b("div",n),H=!!(u||f),W=Mt("button",{className:ya("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!H&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:c||Pn.actionIconColor,backgroundColor:p||void 0,border:H?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),I=he(d,o,"currentColor",1);if(I&&(I.style.display="block",W.appendChild(I)),P.appendChild(W),E&&S){let re=null,Se=()=>{if(re)return;let ae=W.ownerDocument,ie=ae.body;if(!ie)return;re=Dr(ae,"div","persona-clear-chat-tooltip"),re.textContent=S;let ye=Dr(ae,"div");ye.className="persona-clear-chat-tooltip-arrow",re.appendChild(ye);let je=W.getBoundingClientRect();re.style.position="fixed",re.style.zIndex=String(Do),re.style.left=`${je.left+je.width/2}px`,re.style.top=`${je.top-8}px`,re.style.transform="translate(-50%, -100%)",ie.appendChild(re)},oe=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};P.addEventListener("mouseenter",Se),P.addEventListener("mouseleave",oe),W.addEventListener("focus",Se),W.addEventListener("blur",oe),P._cleanupTooltip=()=>{oe(),P.removeEventListener("mouseenter",Se),P.removeEventListener("mouseleave",oe),W.removeEventListener("focus",Se),W.removeEventListener("blur",oe)}}return{button:W,wrapper:P}};var Pn={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))"},no=e=>{var I,T,B,q,U,L,F,_,ee,Me,pe,te,Pe,Ie,re,Se;let{config:t,showClose:n=!0}=e,r=Mt("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)))"}}),o=(I=t==null?void 0:t.launcher)!=null?I:{},s=(T=o.headerIconSize)!=null?T:"48px",a=(B=o.closeButtonPlacement)!=null?B:"inline",i=(q=o.headerIconHidden)!=null?q:!1,d=o.headerIconName,c=Mt("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(d){let oe=parseFloat(s)||24,ae=he(d,oe*.6,"currentColor",1);ae?c.replaceChildren(ae):c.textContent=(L=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?L:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let oe=b("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(ee=(_=t==null?void 0:t.launcher)==null?void 0:_.agentIconText)!=null?ee:"\u{1F4AC}";let p=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Mt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Me=t==null?void 0:t.launcher)==null?void 0:Me.title)!=null?pe:"Chat Assistant",style:{color:Pn.titleColor}}),f=Mt("span",{className:"persona-text-xs",text:(Pe=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Ie=o.clearChat)!=null?Ie:{},y=(re=g.enabled)!=null?re:!0,v=(Se=g.placement)!=null?Se:"inline",S=null,E=null;if(y){let ae=_i(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=ae.button,E=ae.wrapper,v==="top-right"&&(E.style.right="48px"),v==="inline"&&r.appendChild(E)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:W}=Fi(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&r.appendChild(W),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:H,closeButtonWrapper:W,clearChatButton:S,clearChatButtonWrapper:E}},ps=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Fo(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=b("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(Do)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",g.id),g.destructive&&y.setAttribute("data-destructive",""),g.icon){let S=he(g.icon,16,"currentColor",1.5);S&&y.appendChild(S)}let v=document.createElement("span");v.textContent=g.label,y.appendChild(v),y.addEventListener("click",S=>{S.stopPropagation(),p(),n(g.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=y=>{!a.contains(y.target)&&!r.contains(y.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=he(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Na(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=b("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=he(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=b("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function Oa(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=b("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=b("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function $i(e){var g,y;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=b("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=he(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,S;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Fo({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var sc=e=>{var r;let t=no({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.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 jb(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=he(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=Fo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ac=e=>{var P,H,W,I,T,B,q,U,L;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(P=t==null?void 0:t.launcher)!=null?P:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=$i({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,p=(W=c.querySelector(".persona-combo-btn-label"))!=null?W:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=b("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pn.titleColor,p.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(p),jb(c,o==null?void 0:o.trailingActions,(T=o==null?void 0:o.onAction)!=null?T:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let _=o.onTitleClick;c.addEventListener("click",ee=>{ee.target.closest("button")||_()}),c.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),_())})}let F=o==null?void 0:o.titleRowHover;F&&(c.style.borderRadius=(B=F.borderRadius)!=null?B:"10px",c.style.padding=(q=F.padding)!=null?q:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var _,ee;c.style.backgroundColor=(_=F.background)!=null?_:"",c.style.borderColor=(ee=F.border)!=null?ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(U=a.closeButtonSize)!=null?U:"32px",f=b("div",""),g=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Pn.actionIconColor;let y=(L=a.closeButtonIconName)!=null?L:"x",v=he(y,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let S=b("div");S.style.display="none";let E=b("span");return E.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:E,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ji={default:sc,minimal:ac},ic=e=>{var t;return(t=ji[e])!=null?t:ji.default},Ks=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=b("div");p.style.display="none";let u=b("span"),f=b("span"),g=b("button");g.style.display="none";let y=b("div");return y.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=ic(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(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 Ui=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},qi=e=>{var I,T,B,q,U,L,F,_,ee,Me,pe,te;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(T=t.useIcon)!=null?T:!1,r=(B=t.iconText)!=null?B:"\u2191",o=t.iconName,s=(q=t.stopIconName)!=null?q:"square",a=(U=t.tooltipText)!=null?U:"Send message",i=(L=t.stopTooltipText)!=null?L:"Stop generating",d=(_=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?_:"Send",c=(Me=(ee=e==null?void 0:e.copy)==null?void 0:ee.stopButtonLabel)!=null?Me:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(te=t.size)!=null?te:"40px",f=t.backgroundColor,g=t.textColor,y=b("div","persona-send-button-wrapper"),v=Mt("button",{className:ya("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&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||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}}),S=null,E=null;if(n){let Pe=parseFloat(u)||24,Ie=(g==null?void 0:g.trim())||"currentColor";o?(S=he(o,Pe,Ie,2),S?v.appendChild(S):v.textContent=r):v.textContent=r,E=he(s,Pe,Ie,2)}else v.textContent=d;let P=null;p&&a&&(P=b("div","persona-send-button-tooltip"),P.textContent=a,y.appendChild(P)),v.setAttribute("aria-label",a),y.appendChild(v);let H="send";return{button:v,wrapper:y,setMode:Pe=>{if(Pe===H)return;H=Pe;let Ie=Pe==="stop"?i:a;if(v.setAttribute("aria-label",Ie),P&&(P.textContent=Ie),n){if(S&&E){let re=Pe==="stop"?E:S;v.replaceChildren(re)}}else v.textContent=Pe==="stop"?c:d}}},zi=e=>{var P,H,W,I,T,B,q,U,L,F,_,ee;let t=(P=e==null?void 0:e.voiceRecognition)!=null?P:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(r||o))return null;let a=(I=(W=e==null?void 0:e.sendButton)==null?void 0:W.size)!=null?I:"40px",i=(T=t.iconName)!=null?T:"mic",d=(B=t.iconSize)!=null?B:a,c=parseFloat(d)||24,p=(U=t.backgroundColor)!=null?U:(q=e==null?void 0:e.sendButton)==null?void 0:q.backgroundColor,u=(F=t.iconColor)!=null?F:(L=e==null?void 0:e.sendButton)==null?void 0:L.textColor,f=b("div","persona-send-button-wrapper"),g=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=he(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let S=(_=t.tooltipText)!=null?_:"Start voice recognition";if(((ee=t.showTooltip)!=null?ee:!1)&&S){let Me=b("div","persona-send-button-tooltip");Me.textContent=S,f.appendChild(Me)}return{button:g,wrapper:f}},Vi=e=>{var y,v,S,E,P,H,W,I;let t=(y=e==null?void 0:e.attachments)!=null?y:{};if(t.enabled!==!0)return null;let n=(S=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?S:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((E=t.allowedTypes)!=null?E:to).join(","),o.multiple=((P=t.maxFiles)!=null?P:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(H=t.buttonIconName)!=null?H:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),p=Mt("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":(W=t.buttonTooltipText)!=null?W:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=he(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",T=>{T.preventDefault(),o.click()}),c.appendChild(p);let f=(I=t.buttonTooltipText)!=null?I:"Attach file",g=b("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},Ki=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=b("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Gi=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Gs=e=>{var y,v,S,E,P,H;let{config:t}=e,n=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Gi(),o=Mt("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}=Ui(t);a();let i=qi(t),d=zi(t),c=Vi(t),p=Ki(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(c==null?void 0:c.button)&&W.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(P=c==null?void 0:c.input)!=null?P:null,attachmentPreviewsContainer:(H=c==null?void 0:c.previewsContainer)!=null?H:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var mf=()=>{let e=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=he("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},gf=e=>{var y,v,S,E,P,H;let{config:t}=e,n=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Gi();r.style.display="none";let o=Ki(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ui(t);s.style.maxHeight="100px",a();let i=qi(t),d=zi(t),c=Vi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",W=>{W.target!==i.button&&W.target!==i.wrapper&&W.target!==(d==null?void 0:d.button)&&W.target!==(d==null?void 0:d.wrapper)&&W.target!==(c==null?void 0:c.button)&&W.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(P=c==null?void 0:c.input)!=null?P:null,attachmentPreviewsContainer:(H=c==null?void 0:c.previewsContainer)!=null?H:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var ff=e=>{var p,u,f,g,y,v,S,E,P,H,W,I,T,B,q,U,L;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=rn(e);if(Oo(e)){let F=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},_=b("div","persona-widget-wrapper persona-fixed persona-transition");_.setAttribute("data-persona-composer-bar",""),_.dataset.state="collapsed",_.dataset.expandedSize=(y=F.expandedSize)!=null?y:"anchored",_.style.zIndex=String((S=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?S:Cn);let ee=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ee.style.width="100%",_.appendChild(ee);let Me=b("div","persona-widget-pill-root");return Me.setAttribute("data-persona-composer-bar",""),Me.dataset.state="collapsed",Me.dataset.expandedSize=(E=F.expandedSize)!=null?E:"anchored",Me.style.zIndex=String((H=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?H:Cn),{wrapper:_,panel:ee,pillRoot:Me}}if(n){let F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),_=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(_),{wrapper:F,panel:_}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),_=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ee=(I=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?I:"100%";return F.style.width=ee,_.style.width="100%",F.appendChild(_),{wrapper:F,panel:_}}let o=(T=e==null?void 0:e.launcher)!=null?T:{},s=o.position&&br[o.position]?br[o.position]:br["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((q=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?q:Cn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(L=(U=e==null?void 0:e.launcher)==null?void 0:U.width)!=null?L:e==null?void 0:e.launcherWidth,c=d!=null?d:zn;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Ub=(e,t)=>{var W,I,T,B,q,U,L,F,_;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Fi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(T=(I=(W=e==null?void 0:e.launcher)==null?void 0:W.clearChat)==null?void 0:I.enabled)!=null?T:!0,a=null,i=null;if(s){let ee=_i(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ee.button,i=ee.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(q=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?q:"Hello \u{1F44B}"}),u=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),f=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),g=b("div","persona-flex persona-flex-col persona-gap-3"),y=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((_=e==null?void 0:e.copy)==null?void 0:_.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let S=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=gf({config:e}),{root:P,textNode:H}=mf();return n.append(d,o,c,S),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:S,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:P,peekTextNode:H}},hf=(e,t=!0)=>{var S,E,P,H,W,I,T,B,q;if(Oo(e))return Ub(e,t);let n=Mt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(S=e==null?void 0:e.layout)==null?void 0:S.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Ks(e,r,{showClose:t}):no({config:e,showClose:t}),a=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:rn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=b("div","persona-flex persona-flex-col persona-gap-3"),u=(T=e==null?void 0:e.layout)==null?void 0:T.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((B=e==null?void 0:e.copy)==null?void 0:B.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=Gs({config:e}),y=((q=e==null?void 0:e.layout)==null?void 0:q.showFooter)!==!1;o?ps(n,s,e):(s.header.style.display="none",ps(n,s,e)),n.append(a);let v=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return y||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var lc=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
20
20
  <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>
21
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
22
22
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -24,14 +24,14 @@ _Details: ${n.message}_`:r}var Ta=e=>({isError:!0,content:[{type:"text",text:e}]
24
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
25
25
  </span>
26
26
  <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>
27
- `,n.addEventListener("click",t);let r=s=>{var I,M,L,C,R,U,j,W,O,F,ee,Me,pe;let a=(I=s.launcher)!=null?I:{},i=on(s),d=n.querySelector("[data-role='launcher-title']");if(d){let te=(M=a.title)!=null?M:"Chat Assistant";d.textContent=te,d.setAttribute("title",te)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let te=(L=a.subtitle)!=null?L:"Here to help you get answers fast";c.textContent=te,c.setAttribute("title",te)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let te=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=te,u.style.width=te,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 Pe=parseFloat(te)||24,Ie=he(a.agentIconName,Pe*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(u.appendChild(Ie),u.style.display=""):(u.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(U=a.agentIconText)!=null?U:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let te=(j=a.agentIconSize)!=null?j:"40px";f.style.height=te,f.style.width=te,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let te=(W=a.callToActionIconSize)!=null?W:"32px";g.style.height=te,g.style.width=te,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Pe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Pe=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Ie=parseFloat(te)||24,re=Math.max(Ie-Pe,8),Se=he(a.callToActionIconName,re,"currentColor",2);Se?g.appendChild(Se):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}let b=a.position&&xr[a.position]?xr[a.position]:xr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?T:`${v} ${b}`,i||(n.style.zIndex=String((ee=a.zIndex)!=null?ee:vn));let E="1px solid var(--persona-border, #e5e7eb)",P="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=(Me=a.border)!=null?Me:E,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:P,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=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var of=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=nf(e),s=rf(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={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:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},tc=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>ec(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=ec(e,n);return{instance:o,element:o.element}};var Lb=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}},Pb=(e,t)=>{if(!e)return null;let n=Lb(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Ib=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},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(":"))},nc=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(":"))},rc=320,af=320,Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Bb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Db=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Nb=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let c=y("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${rc}px`,c.style.maxHeight=`${af}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,c.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{p=!0}),Rb(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Ob=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!nc(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${rc}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Fb=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!nc(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${rc}px`,o.style.maxHeight=`${af}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},_b=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!nc(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ds=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},oc=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ds};if(t){let o=t(r);if(o!==null)return o}return ds()},$b=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},sf=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},jb=(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)=>{var b,v,T,E,P,I,M;let r=(b=t.showCopy)!=null?b:!0,o=(v=t.showUpvote)!=null?v:!0,s=(T=t.showDownvote)!=null?T:!0,a=(E=t.showReadAloud)!=null?E:!1;if(!r&&!o&&!s&&!a){let L=y("div");return L.style.display="none",L.id=`actions-${e.id}`,L.setAttribute("data-actions-for",e.id),L}let i=(P=t.visibility)!=null?P:"hover",d=(I=t.align)!=null?I:"right",c=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(L,C,R)=>{let U=Gt({icon:L,label:C,size:14,className:"persona-message-action-btn"});return U.setAttribute("data-action",R),U};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},zs=(e,t,n,r,o,s)=>{var oe,ae,ie,ye,je,K,Y,ke,X,ce,Re,be,Ge,ft,Ht,nt,fe;let a=n!=null?n:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,p=(ae=d==null?void 0:d.show)!=null?ae:!1,u=(ie=c==null?void 0:c.show)!=null?ie:!1,f=(ye=d==null?void 0:d.position)!=null?ye:"left",g=(je=c==null?void 0:c.position)!=null?je:"below",b=jb(e.role,i),v=y("div",b.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Wb(e),E=(Y=(K=e.content)==null?void 0:K.trim())!=null?Y:"",I=T.length>0&&E===gi,M=Pi((X=(ke=s==null?void 0:s.widgetConfig)==null?void 0:ke.features)==null?void 0:X.streamAnimation),L=(be=(Re=(ce=s==null?void 0:s.widgetConfig)==null?void 0:ce.features)==null?void 0:Re.streamAnimation)==null?void 0:be.plugins,C=e.role==="assistant"&&M.type!=="none"?js(M.type,L):null,R=e.role==="assistant"&&((Ge=C==null?void 0:C.isAnimating)==null?void 0:Ge.call(C,e))===!0,U=e.role==="assistant"&&C!==null&&(!!e.streaming||R);U&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),U&&C&&(C.containerClass&&j.classList.add(C.containerClass),j.style.setProperty("--persona-stream-step",`${M.speed}ms`),j.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let W=U?Ii((ft=e.content)!=null?ft:"",M.buffer,C,e,!!e.streaming):(Ht=e.content)!=null?Ht:"",O=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),F=O;U&&(C==null?void 0:C.wrap)==="char"?F=Pa(O,"char",e.id,{skipTags:C.skipTags}):U&&(C==null?void 0:C.wrap)==="word"&&(F=Pa(O,"word",e.id,{skipTags:C.skipTags}));let ee=null;if(I?(ee=document.createElement("div"),ee.innerHTML=F,ee.style.display="none",j.appendChild(ee)):j.innerHTML=F,U&&(C!=null&&C.useCaret)&&!I&&E){let Q=Ri(),lt=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ke=lt[lt.length-1];if(Ke!=null&&Ke.parentNode)Ke.parentNode.insertBefore(Q,Ke.nextSibling);else{let Te=j.lastElementChild;Te?Te.appendChild(Q):j.appendChild(Q)}}if(u&&g==="inline"&&e.createdAt){let Q=sf(e,c,"span");Q.classList.add("persona-timestamp-inline");let lt=j.lastElementChild;lt?lt.appendChild(Q):j.appendChild(Q)}if(T.length>0){let Q=Nb(T,!I&&!!E,()=>{I&&ee&&(ee.style.display="")});Q?v.appendChild(Q):I&&ee&&(ee.style.display="")}let Me=Hb(e);if(Me.length>0){let Q=Ob(Me);Q&&v.appendChild(Q)}let pe=Bb(e);if(pe.length>0){let Q=Fb(pe);Q&&v.appendChild(Q)}let te=Db(e);if(te.length>0){let Q=_b(te);Q&&v.appendChild(Q)}if(v.appendChild(j),u&&g==="below"&&e.createdAt){let Q=sf(e,c);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let Pe=e.role==="assistant"?Pb(e.stopReason,(fe=(nt=s==null?void 0:s.widgetConfig)==null?void 0:nt.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(W&&W.trim()),lt=M.placeholder==="skeleton",Ke=lt&&M.buffer==="line"&&Q;if(Q)Ke&&v.appendChild(Ia());else if(lt)v.appendChild(Ia());else{let Te=oc("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Te&&v.appendChild(Te)}}if(Pe&&e.stopReason&&!e.streaming&&(E||(j.style.display="none"),v.appendChild(Ib(e.stopReason,Pe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=sc(e,r,o);v.appendChild(Q)}if(!p||e.role==="system")return v;let re=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=$b(d,e.role);return f==="right"||f==="left"&&e.role==="user"?re.append(v,Se):re.append(Se,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),re},lf=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):zs(e,t,n,r,o,s)};var Vs=new Set,Ub=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),qb=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},cf=(e,t)=>{let n=Vs.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=he(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ac=(e,t)=>{var pe,te,Pe,Ie,re,Se,oe,ae,ie,ye,je;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(te=(pe=t==null?void 0:t.features)==null?void 0:pe.reasoningDisplay)!=null?te:{},s=o.expandable!==!1,a=s&&Vs.has(e.id),i=n.status!=="complete",d=qb(e,(Pe=o.previewMaxLines)!=null?Pe:3),c=y("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");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Ie=t==null?void 0:t.reasoning)!=null?Ie:{},b=String((re=n.startedAt)!=null?re:Date.now()),v=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",b),K.textContent=ii(n),K},T=(Se=g.renderCollapsedSummary)==null?void 0:Se.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ii(n),createElapsedElement:v});typeof T=="string"&&T.trim()?(u.textContent=T,p.appendChild(u)):T instanceof HTMLElement?p.appendChild(T):(u.textContent=f,p.appendChild(u));let E=y("span","persona-text-xs persona-text-persona-primary");E.textContent=og(n),p.appendChild(E);let P=(oe=o.loadingAnimation)!=null?oe:"none",I=g.activeTextTemplate,M=g.completeTextTemplate,L=i?I:M,C=T instanceof HTMLElement,R=(K,Y,ke)=>{let X=ke;for(let ce of Y){let Re=y("span","persona-tool-char");Re.style.setProperty("--char-index",String(X)),Re.textContent=ce===" "?"\xA0":ce,K.appendChild(Re),X++}return X},U=(K,Y)=>{u.textContent="";let ke=li(K,""),X=0;for(let ce of ke){let Re=ce.styles.length>0?(()=>{let be=y("span",ce.styles.map(Ge=>`persona-tool-text-${Ge}`).join(" "));return u.appendChild(be),be})():u;if(ce.isDuration&&i)Re.appendChild(v());else{let be=ce.isDuration?ii(n):ce.text;Y?X=R(Re,be,X):Re.appendChild(document.createTextNode(be))}}};if(!C&&L)if(E.style.display="none",u.style.display="",i&&P!=="none"){let K=(ae=g.loadingAnimationDuration)!=null?ae:2e3;u.setAttribute("data-preserve-animation","true"),P==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),U(L,!1)):(u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),P==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),U(L,!0))}else U(L,!1);else if(!C&&i&&P!=="none"){u.style.display="";let K=(ie=g.loadingAnimationDuration)!=null?ie:2e3;if(u.setAttribute("data-preserve-animation","true"),P==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),P==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Y=u.textContent||f;u.textContent="",R(u,Y,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=y("div","persona-flex persona-items-center");let Y=he(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?j.appendChild(Y):j.textContent=a?"Hide":"Show";let ke=y("div","persona-flex persona-items-center persona-ml-auto");ke.append(j),c.append(p,ke)}else c.append(p);let W=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(je=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:je.call(ye,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Ub(W,K)||(W.textContent=d),W.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,W),r;let O=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let F=n.chunks.join(""),ee=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ee.textContent=F||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(ee),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let Y=he(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?j.appendChild(Y):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(c,W,O),r};var Ks=new Set,zb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vb=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
- `);let o=ko(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
- `):""},ic=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Kb=(e,t)=>{var p,u,f,g,b;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=Vb(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?sg(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return o==="tool-name"?c=((b=n.name)==null?void 0:b.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Dl(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Dl(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},df=(e,t,n)=>{var p;let r=Ks.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},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",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",f=he(r?"chevron-up":"chevron-down",16,u,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},lc=(e,t)=>{var F,ee,Me,pe,te,Pe,Ie,re,Se;let n=e.toolCall,r=(F=t==null?void 0:t.toolCall)!=null?F:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Me=(ee=t==null?void 0:t.features)==null?void 0:ee.toolCallDisplay)!=null?Me:{},a=s.expandable!==!1,i=a&&Ks.has(e.id),{summary:d,previewText:c,isActive:p}=Kb(e,t),u=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let b=String((pe=n.startedAt)!=null?pe:Date.now()),v=()=>{let oe=y("span","");return oe.setAttribute("data-tool-elapsed",b),oe.textContent=va(n),oe},T=(Pe=r.renderCollapsedSummary)==null?void 0:Pe.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(te=s.collapsedMode)!=null?te:"tool-call",isActive:p,config:t!=null?t:{},elapsed:va(n),createElapsedElement:v});typeof T=="string"&&T.trim()?(g.textContent=T,f.appendChild(g)):T instanceof HTMLElement?f.appendChild(T):(g.textContent=d,f.appendChild(g));let E=(Ie=s.loadingAnimation)!=null?Ie:"none",P=r.activeTextTemplate,I=r.completeTextTemplate,M=p?P:I,L=T instanceof HTMLElement,C=(oe,ae,ie)=>{let ye=ie;for(let je of ae){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(ye)),K.textContent=je===" "?"\xA0":je,oe.appendChild(K),ye++}return ye},R=(oe,ae)=>{var K;g.textContent="";let ie=((K=n.name)==null?void 0:K.trim())||"tool",ye=li(oe,ie),je=0;for(let Y of ye){let ke=Y.styles.length>0?(()=>{let X=y("span",Y.styles.map(ce=>`persona-tool-text-${ce}`).join(" "));return g.appendChild(X),X})():g;if(Y.isDuration&&p)ke.appendChild(v());else{let X=Y.isDuration?va(n):Y.text;ae?je=C(ke,X,je):ke.appendChild(document.createTextNode(X))}}};if(!L)if(p&&E!=="none"){let oe=(re=r.loadingAnimationDuration)!=null?re:2e3;if(g.setAttribute("data-preserve-animation","true"),E==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),M&&R(M,!1);else if(g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)R(M,!0);else{let ae=g.textContent||d;g.textContent="",C(g,ae,0)}}else M&&R(M,!1);let U=null;if(a){U=y("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=he(i?"chevron-up":"chevron-down",16,oe,2);ae?U.appendChild(ae):U.textContent=i?"Hide":"Show";let ie=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(U),u.append(f,ie)}else u.append(f);let j=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let oe=(Se=r.renderCollapsedPreview)==null?void 0:Se.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});zb(j,oe)||(j.textContent=c),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let W=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),n.name){let oe=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=n.name,W.appendChild(oe)}if(n.args!==void 0){let oe=y("div","persona-space-y-1"),ae=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Arguments";let ie=y("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",ic(ie,r),ie.textContent=ko(n.args),oe.append(ae,ie),W.appendChild(oe)}if(n.chunks&&n.chunks.length){let oe=y("div","persona-space-y-1"),ae=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Activity";let ie=y("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",ic(ie,r),ie.textContent=n.chunks.join(""),oe.append(ae,ie),W.appendChild(oe)}if(n.status==="complete"&&n.result!==void 0){let oe=y("div","persona-space-y-1"),ae=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Result";let ie=y("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",ic(ie,r),ie.textContent=ko(n.result),oe.append(ae,ie),W.appendChild(oe)}if(n.status==="complete"&&typeof n.duration=="number"){let oe=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${n.duration}ms`,W.appendChild(oe)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),U){U.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=he(i?"chevron-up":"chevron-down",16,oe,2);ae?U.appendChild(ae):U.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,W),o};var ps=new Map,qi=e=>{let n=(e.startsWith(yr)?e.slice(yr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},pf=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,uf=(e,t)=>{var r,o,s;let n=(o=(r=pf(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ps.get(e))!=null?s:n==="expanded"},mf=(e,t,n)=>{var a,i;let r=pf(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=he(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},gf=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=uf(e,n);mf(r,s,n),o.style.display=s?"":"none"};var zi=(e,t)=>{var R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(R=r==null?void 0:r.backgroundColor)!=null?R:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(U=r==null?void 0:r.borderColor)!=null?U:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(j=r==null?void 0:r.titleColor)!=null?j:"currentColor",p=he(d,20,c,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(W=r==null?void 0:r.title)!=null?W:"Approval Required",f.appendChild(g),!o){let ae=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ae.setAttribute("data-approval-status",n.status),n.status==="approved"?(ae.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ae.style.color="var(--persona-palette-colors-success-700, #15803d)",ae.textContent="Approved"):n.status==="denied"?(ae.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ae.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ae.textContent="Denied"):n.status==="timeout"&&(ae.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ae.style.color="var(--persona-palette-colors-warning-700, #b45309)",ae.textContent="Timeout"),f.appendChild(ae)}u.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(yr)?ua(n.toolName):void 0,T=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),E=!n.toolName,P=T||(E?n.description:`The assistant wants to use \u201C${v!=null?v:qi(n.toolName)}\u201D.`),I=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(I.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(I.style.color=r.descriptionColor),I.textContent=P,u.appendChild(I),n.reason){let ae=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ae.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?ae.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let ie=y("span","persona-font-medium");ie.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,ae.appendChild(ie),ae.appendChild(document.createTextNode(n.reason)),u.appendChild(ae)}let M=(ee=r==null?void 0:r.detailsDisplay)!=null?ee:"collapsed",L=!!n.description&&!E,C=L||!!n.parameters;if(M!=="hidden"&&C){let ae=uf(e.id,t),ie=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ie.type="button",ie.setAttribute("data-expand-header","true"),ie.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let ye=y("span");ye.setAttribute("data-approval-details-label","true");let je=y("span","persona-inline-flex persona-items-center");je.setAttribute("data-approval-details-chevron","true"),ie.append(ye,je),mf(ie,ae,t),u.appendChild(ie);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=ae?"":"none",L){let Y=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Y.style.color=r.descriptionColor),Y.textContent=n.description,K.appendChild(Y)}if(n.parameters){let Y=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(Y.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Y.style.color=r.parameterTextColor),Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Y.textContent=ko(n.parameters),K.appendChild(Y)}u.appendChild(K)}if(o){let ae=y("div","persona-flex persona-gap-2 persona-mt-2");ae.setAttribute("data-approval-buttons","true");let ie=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ie.type="button",ie.style.backgroundColor=(Me=r==null?void 0:r.approveButtonColor)!=null?Me:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",ie.setAttribute("data-approval-action","approve");let ye=he("shield-check",14,(te=r==null?void 0:r.approveButtonTextColor)!=null?te:"#ffffff",2);ye&&(ye.style.marginRight="4px",ie.appendChild(ye));let je=document.createTextNode((Pe=r==null?void 0:r.approveLabel)!=null?Pe:"Approve");ie.appendChild(je);let K=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ie=r==null?void 0:r.denyButtonColor)!=null?Ie:"transparent",K.style.color=(re=r==null?void 0:r.denyButtonTextColor)!=null?re:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let Y=he("shield-x",14,(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",2);Y&&(Y.style.marginRight="4px",K.appendChild(Y));let ke=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");K.appendChild(ke),ae.append(ie,K),u.appendChild(ae)}return a.append(i,u),s.appendChild(a),s};function Gb(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function ff(e){var v;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,c=(v=e.container)!=null?v:Gb(t),p=!1,u=null,f=()=>{if(!p)return;let T=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${T.width}px`);let E=r==="top-start"||r==="top-end"?T.top-o-n.getBoundingClientRect().height:T.bottom+o,P=r==="bottom-end"||r==="top-end"?T.right-n.getBoundingClientRect().width:T.left;n.style.top=`${E}px`,n.style.left=`${P}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},b=()=>{var L,C,R;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),f();let T=(C=((L=t.ownerDocument)!=null?L:document).defaultView)!=null?C:window,E=(R=t.ownerDocument)!=null?R:document,P=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},I=U=>{let j=typeof U.composedPath=="function"?U.composedPath():[];j.includes(n)||j.includes(t)||(g(),d==null||d("outside"))},M=T.setTimeout(()=>{E.addEventListener("pointerdown",I,!0)},0);T.addEventListener("scroll",P,!0),T.addEventListener("resize",P),u=()=>{T.clearTimeout(M),E.removeEventListener("pointerdown",I,!0),T.removeEventListener("scroll",P,!0),T.removeEventListener("resize",P)},i==null||i()};return{get isOpen(){return p},open:b,close:g,toggle:()=>p?g():b(),reposition:f,destroy:g}}function hf(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Jb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),yf=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},us=(e,t)=>{yf(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)},Xb=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Qb=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ps.get(e))!=null?o:n==="expanded"},cc=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Yb=(e,t)=>{var c,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(yr)?ua(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(c=e.description)!=null?c:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:qi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},Zb=e=>{let t=y("div","persona-approval-resolved"),n=he("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?qi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},ex=(e,t,n,r,o,s,a)=>{var U,j,W,O,F,ee,Me;let i=y("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"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(U=r==null?void 0:r.detailsDisplay)!=null?U:"collapsed",c=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=c||p,f=u&&Qb(t.id,r),g=(j=r==null?void 0:r.showDetailsLabel)!=null?j:"Show details",b=(W=r==null?void 0:r.hideDetailsLabel)!=null?W:"Hide details",v=y("button","persona-approval-head");v.type="button",u?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",f?"true":"false"),v.setAttribute("aria-label",f?b:g)):v.setAttribute("data-static","true");let T=y("span","persona-approval-logo"),E=he("shield-check",16,"currentColor",2);E&&T.appendChild(E),v.appendChild(T);let P=Yb(n,r);if(u){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let te=he("chevron-down",14,"currentColor",2);te&&pe.appendChild(te),P.append(" "),P.appendChild(pe)}v.appendChild(P),i.appendChild(v);let I=y("div","persona-approval-body");if(u){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!f,c){let te=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=n.description,pe.appendChild(te)}if(p){let te=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(te.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.textContent=ko(n.parameters),pe.appendChild(te)}I.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let te=y("span","persona-approval-reason-label");te.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,pe.append(te,document.createTextNode(n.reason)),I.appendChild(pe)}let M=y("div","persona-approval-actions"),L=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},R=y("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(R.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(R.style.color=r.denyButtonTextColor),R.append((F=r==null?void 0:r.denyLabel)!=null?F:"Deny"),a){let pe=y("div","persona-approval-split"),te=y("button","persona-approval-primary");te.type="button",te.setAttribute("data-action","always"),C(te),te.append((ee=r==null?void 0:r.approveLabel)!=null?ee:"Always allow",cc("\u23CE"));let Pe=y("button","persona-approval-caret");Pe.type="button",Pe.setAttribute("data-action","toggle-menu"),Pe.setAttribute("aria-label","More options"),C(Pe);let Ie=he("chevron-down",15,"currentColor",2);Ie&&Pe.appendChild(Ie),pe.append(te,Pe),M.append(pe,R),R.append(cc("Esc"));let re=y("div","persona-approval-menu"),Se=y("button","persona-approval-menu-item");Se.type="button",Se.append("Allow once",cc("\u2318\u23CE")),re.appendChild(Se),L=ff({anchor:pe,content:re,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,L),Se.addEventListener("click",()=>{us(e,t.id),o()})}else{let pe=y("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),C(pe),pe.append((Me=r==null?void 0:r.approveLabel)!=null?Me:"Allow"),M.append(pe,R)}return I.appendChild(M),i.appendChild(I),i.addEventListener("click",pe=>{let te=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!te)return;let Pe=te.getAttribute("data-action");if(Pe==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let re=Ie.hidden;Ie.hidden=!re,v.setAttribute("aria-expanded",re?"true":"false"),v.setAttribute("aria-label",re?b:g),ps.set(t.id,re)}return}if(Pe==="toggle-menu"){L==null||L.toggle();return}if(Pe==="always"){us(e,t.id),o({remember:!0});return}if(Pe==="allow"){us(e,t.id),o();return}if(Pe==="deny"){us(e,t.id),s();return}}),i},bf=()=>{let e=Jb();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Xb(a);if(i.status!=="pending"){if(us(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Zb(i)}yf(e,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=ex(e,r,i,d,o,s,c);if(c){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=f=>{hf(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),us(e,r.id),f.key==="Escape"?s():f.metaKey||f.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])us(e,r);e.latestPendingApprovalId=null}}};var xf=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(T=>T.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=b=>{switch(b){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(o.forEach(b=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=b,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),u.appendChild(v),t.push(v)}),e.appendChild(u),p){let b=JSON.stringify(o);b!==n&&(n=b,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Da=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Na=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}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(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var tx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),nx=new Set(["step_start","execution_start"]),rx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),ox=new Set(["step_complete","agent_turn_complete"]),sx=new Set(["flow_complete","agent_complete"]),vf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Cf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ms=(e,t)=>{let n=e[t];return Cf(n)?n:void 0};function dc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Vi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function ax(e,t){return typeof t.type=="string"?t.type:e}function ix(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 lx(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 wf(e){var r,o,s,a,i;let t=ms(e,"result"),n=[ms(e,"tokens"),ms(e,"totalTokens"),t?ms(t,"tokens"):void 0,ms(e,"usage"),t?ms(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=Kn(d.output))!=null?r:Kn(d.outputTokens))!=null?o:Kn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Kn(e.outputTokens))!=null?s:Kn(e.completionTokens))!=null?i:t?(a=Kn(t.outputTokens))!=null?a:Kn(t.completionTokens):void 0}function cx(e){var n,r,o,s,a;let t=ms(e,"result");return(a=(o=(r=(n=Kn(e.executionTime))!=null?n:Kn(e.executionTimeMs))!=null?r:Kn(e.execution_time))!=null?o:Kn(e.duration))!=null?a:t?(s=Kn(t.executionTime))!=null?s:Kn(t.executionTimeMs):void 0}function dx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Oa=class{constructor(t=dx){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:Vi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!Cf(n)){vf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=ax(t,n),o=this.now();if(tx.has(r)){this.startRun(o);return}if(nx.has(r)){this.run||this.startRun(o);return}if(rx.has(r)){if(!lx(r,n))return;let a=ix(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+dc(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Vi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(ox.has(r)){if(!this.run)return;let a=this.run,i=wf(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+dc(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Vi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(sx.has(r)){if(!this.run)return;let a=this.run,i=wf(n),d=i!=null?i:a.exactOutputTokens+dc(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Vi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(vf.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=cx(n);return s!=null?s:r-t.startedAt}};function Gs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var px={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)"}},ux={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},mx=["flowName","stepName","reasoningText","text","name","tool","toolName"],gx=100;function fx(e,t){let n={...px,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return ux}function hx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function yx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function bx(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)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 xx(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function vx(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 wx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Cx(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 Ax(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function pc(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Gs(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){var F,ee;let g=y("div",""),b=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");b.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=he(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&v.appendChild(T);let E=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=(F=r.timestampFormat)!=null?F:"relative";E.textContent=P==="relative"?hx(e.timestamp,n):yx(e.timestamp);let I=null;r.showSequenceNumbers!==!1&&(I=y("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 M=fx(e.type,r.badgeColors),L=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=M.bg,L.style.color=M.text,L.style.borderColor=M.text+"50",L.textContent=e.type;let C=(ee=r.descriptionFields)!=null?ee:mx,R=bx(e.payload,C),U=null;R&&(U=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=R);let j=y("div","persona-flex-1 persona-min-w-0"),W=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=he("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Me=>{Me.stopPropagation(),await xx(vx(e)),W.innerHTML="";let pe=he("check","12px","currentColor",1.5);pe&&W.appendChild(pe),setTimeout(()=>{W.innerHTML="";let te=he("clipboard","12px","currentColor",1.5);te&&W.appendChild(te)},1500)}),b.appendChild(v),b.appendChild(E),I&&b.appendChild(I),b.appendChild(L),U&&b.appendChild(U),b.appendChild(j),b.appendChild(W),g.appendChild(b),d&&g.appendChild(Ax(e,a,i)),g}}function Af(e){var b,v,T,E,P;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(b=o==null?void 0:o.features)==null?void 0:b.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(T=i==null?void 0:i.label)!=null?T:"",u=(P=(E=o==null?void 0:o.features)==null?void 0:E.eventStream)!=null?P:{},f=s.find(I=>I.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let I=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return g();function g(){let I=u.classNames,M=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Gs(M,I==null?void 0:I.panel);let L=[],C="",R="",U=null,j=[],W={},O=0,F=Mi(),ee=0,Me=0,pe=!1,te=null,Pe=!1,Ie=0,re=new Set,Se=new Map,oe="",ae="",ie=null,ye,je,K,Y,ke=null,X=null,ce=null;function Re(){let ge=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),D=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Gs(D,I==null?void 0:I.headerBar),a){X=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),X.style.cursor="help",ke=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ke.textContent="-- tok/s",ce=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ce.style.display="none",ce.style.pointerEvents="none";let Ft=X,tn=ce,Cr=()=>{if(!tn.textContent)return;let ar=Ft.getBoundingClientRect(),ir=ge.getBoundingClientRect();tn.style.left=`${ar.left-ir.left}px`,tn.style.top=`${ar.bottom-ir.top+4}px`,tn.style.display="block"},Fr=()=>{tn.style.display="none"};X.addEventListener("mouseenter",Cr),X.addEventListener("mouseleave",Fr),X.appendChild(ke)}let ve=y("div","persona-flex-1");ye=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let de=y("option","");de.value="",de.textContent="All events (0)",ye.appendChild(de),je=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),je.type="button",je.title="Copy All";let Xe=he("clipboard-copy","12px","currentColor",1.5);Xe&&je.appendChild(Xe);let Pt=y("span","persona-event-copy-all persona-text-xs");Pt.textContent="Copy All",je.appendChild(Pt),X&&D.appendChild(X),D.appendChild(ve),D.appendChild(ye),D.appendChild(je);let kt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Gs(kt,I==null?void 0:I.searchBar);let vt=he("search","14px","var(--persona-muted, #9ca3af)",1.5),Wt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");vt&&Wt.appendChild(vt),K=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Gs(K,I==null?void 0:I.searchInput),K.type="text",K.placeholder="Search event payloads...",Y=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Y.type="button",Y.style.display="none";let Qt=he("x","12px","currentColor",2);return Qt&&Y.appendChild(Qt),kt.appendChild(Wt),kt.appendChild(K),kt.appendChild(Y),ge.appendChild(D),ge.appendChild(kt),ce&&ge.appendChild(ce),ge}let be,Ge=s.find(ge=>ge.renderEventStreamToolbar);if(Ge!=null&&Ge.renderEventStreamToolbar&&o){let ge=Ge.renderEventStreamToolbar({config:o,defaultRenderer:()=>Re(),eventCount:t.getSize(),filteredCount:0,onFilterChange:D=>{C=D,xe(),At()},onSearchChange:D=>{R=D,xe(),At()}});be=ge!=null?ge:Re()}else be=Re();let ft=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");ft.style.display="none";function Ht(){if(!a||!ke||!X)return;let ge=a(),D=wx(ge);ke.textContent=D;let ve=Cx(ge);ce&&(ce.textContent=ve,ve||(ce.style.display="none")),X.setAttribute("aria-label",ve?`Throughput: ${D}, ${ve}`:`Throughput: ${D}`)}let nt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.style.height="100%";let Q=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Gs(Q,I==null?void 0:I.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let lt=he(c,"14px","currentColor",2);lt&&Q.appendChild(lt);let Ke=y("span","");Ke.textContent=p,Q.appendChild(Ke);let Te=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Te.style.display="none",nt.appendChild(fe),nt.appendChild(Te),nt.appendChild(Q),M.setAttribute("tabindex","0"),M.appendChild(be),M.appendChild(ft),M.appendChild(nt);function Ce(){let ge=t.getAll(),D={};for(let kt of ge)D[kt.type]=(D[kt.type]||0)+1;let ve=Object.keys(D).sort(),de=ve.length!==j.length||!ve.every((kt,vt)=>kt===j[vt]),ht=!de&&ve.some(kt=>D[kt]!==W[kt]),Xe=ge.length!==Object.values(W).reduce((kt,vt)=>kt+vt,0);if(!de&&!ht&&!Xe||(j=ve,W=D,!ye))return;let Pt=ye.value;if(ye.options[0].textContent=`All events (${ge.length})`,de){for(;ye.options.length>1;)ye.remove(1);for(let kt of ve){let vt=y("option","");vt.value=kt,vt.textContent=`${kt} (${D[kt]||0})`,ye.appendChild(vt)}Pt&&ve.includes(Pt)?ye.value=Pt:Pt&&(ye.value="",C="")}else for(let kt=1;kt<ye.options.length;kt++){let vt=ye.options[kt];vt.textContent=`${vt.value} (${D[vt.value]||0})`}}function et(){let ge=t.getAll();if(C&&(ge=ge.filter(D=>D.type===C)),R){let D=R.toLowerCase();ge=ge.filter(ve=>ve.type.toLowerCase().includes(D)||ve.payload.toLowerCase().includes(D))}return ge}function zt(){return C!==""||R!==""}function xe(){O=0,ee=0,F.resume(),Q.style.display="none"}function ue(ge){re.has(ge)?re.delete(ge):re.add(ge),ie=ge;let D=fe.scrollTop,ve=F.isFollowing();Pe=!0,F.pause(),At(),fe.scrollTop=D,ve&&F.resume(),Pe=!1}function wn(){return Wo(fe,50)}function At(){Me=Date.now(),pe=!1,Ht(),Ce();let ge=t.getEvictedCount();ge>0?(ft.textContent=`${ge.toLocaleString()} older events truncated`,ft.style.display=""):ft.style.display="none",L=et();let D=L.length,ve=t.getSize()>0;D===0&&ve&&zt()?(Te.textContent=R?`No events matching '${R}'`:"No events matching filter",Te.style.display="",fe.style.display="none"):(Te.style.display="none",fe.style.display=""),je&&(je.title=zt()?`Copy Filtered (${D})`:"Copy All"),d&&!F.isFollowing()&&D>O&&(ee+=D-O,Ke.textContent=p?`${p}${ee>0?` (${ee})`:""}`:"",Q.style.display=""),O=D;let de=t.getAll(),ht=de.length>0?de[0].timestamp:0,Xe=new Set(L.map(vt=>vt.id));for(let vt of re)Xe.has(vt)||re.delete(vt);let Pt=C!==oe||R!==ae,kt=Se.size===0&&L.length>0;if(Pt||kt||L.length===0){fe.innerHTML="",Se.clear();let vt=document.createDocumentFragment();for(let Wt=0;Wt<L.length;Wt++){let Qt=pc(L[Wt],Wt,ht,u,re,ue,s,o);Se.set(L[Wt].id,Qt),vt.appendChild(Qt)}fe.appendChild(vt),oe=C,ae=R,ie=null}else{if(ie!==null){let Wt=Se.get(ie);if(Wt&&Wt.parentNode===fe){let Qt=L.findIndex(Ft=>Ft.id===ie);if(Qt>=0){let Ft=pc(L[Qt],Qt,ht,u,re,ue,s,o);fe.insertBefore(Ft,Wt),Wt.remove(),Se.set(ie,Ft)}}ie=null}let vt=new Set(L.map(Wt=>Wt.id));for(let[Wt,Qt]of Se)vt.has(Wt)||(Qt.remove(),Se.delete(Wt));for(let Wt=0;Wt<L.length;Wt++){let Qt=L[Wt];if(!Se.has(Qt.id)){let Ft=pc(Qt,Wt,ht,u,re,ue,s,o);Se.set(Qt.id,Ft),fe.appendChild(Ft)}}}F.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function hn(){if(Date.now()-Me>=gx){te!==null&&(cancelAnimationFrame(te),te=null),At();return}pe||(pe=!0,te=requestAnimationFrame(()=>{te=null,At()}))}let vr=(ge,D)=>{if(!je)return;je.innerHTML="";let ve=he(ge,"12px","currentColor",1.5);ve&&je.appendChild(ve);let de=y("span","persona-text-xs");de.textContent="Copy All",je.appendChild(de),setTimeout(()=>{je.innerHTML="";let ht=he("clipboard-copy","12px","currentColor",1.5);ht&&je.appendChild(ht);let Xe=y("span","persona-text-xs");Xe.textContent="Copy All",je.appendChild(Xe),je.disabled=!1},D)},wr=async()=>{if(je){je.disabled=!0;try{let ge;zt()?ge=L:n?(ge=await n(),ge.length===0&&(ge=t.getAll())):ge=t.getAll();let D=ge.map(ve=>{try{return JSON.parse(ve.payload)}catch{return ve.payload}});await navigator.clipboard.writeText(JSON.stringify(D,null,2)),vr("check",1500)}catch{vr("x",1500)}}},qe=()=>{ye&&(C=ye.value,xe(),At())},k=()=>{!K||!Y||(Y.style.display=K.value?"":"none",U&&clearTimeout(U),U=setTimeout(()=>{R=K.value,xe(),At()},150))},me=()=>{!K||!Y||(K.value="",R="",Y.style.display="none",U&&clearTimeout(U),xe(),At())},Ee=()=>{if(Pe)return;let ge=fe.scrollTop,{action:D,nextLastScrollTop:ve}=ki({following:F.isFollowing(),currentScrollTop:ge,lastScrollTop:Ie,nearBottom:wn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=ve,D==="resume"?(F.resume(),ee=0,Q.style.display="none"):D==="pause"&&(F.pause(),d&&(Ke.textContent=p,Q.style.display=""))},Le=ge=>{let D=Li({following:F.isFollowing(),deltaY:ge.deltaY,nearBottom:wn(),resumeWhenNearBottom:!0});D==="pause"?(F.pause(),d&&(Ke.textContent=p,Q.style.display="")):D==="resume"&&(F.resume(),ee=0,Q.style.display="none")},Be=()=>{d&&(fe.scrollTop=fe.scrollHeight,F.resume(),ee=0,Q.style.display="none")},rt=ge=>{let D=ge.target;if(!D||D.closest("button"))return;let ve=D.closest("[data-event-id]");if(!ve)return;let de=ve.getAttribute("data-event-id");de&&ue(de)},Ye=ge=>{if((ge.metaKey||ge.ctrlKey)&&ge.key==="f"){ge.preventDefault(),K==null||K.focus(),K==null||K.select();return}ge.key==="Escape"&&(K&&document.activeElement===K?(me(),K.blur(),M.focus()):r&&r())};je&&je.addEventListener("click",wr),ye&&ye.addEventListener("change",qe),K&&K.addEventListener("input",k),Y&&Y.addEventListener("click",me),fe.addEventListener("scroll",Ee),fe.addEventListener("wheel",Le,{passive:!0}),fe.addEventListener("click",rt),Q.addEventListener("click",Be),M.addEventListener("keydown",Ye);function yt(){U&&clearTimeout(U),te!==null&&(cancelAnimationFrame(te),te=null),pe=!1,Se.clear(),je&&je.removeEventListener("click",wr),ye&&ye.removeEventListener("change",qe),K&&K.removeEventListener("input",k),Y&&Y.removeEventListener("click",me),fe.removeEventListener("scroll",Ee),fe.removeEventListener("wheel",Le),fe.removeEventListener("click",rt),Q.removeEventListener("click",Be),M.removeEventListener("keydown",Ye)}return{element:M,update:hn,destroy:yt}}}function Sf(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(c.append(p,u),i.append(d,c),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Tf=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Sf(e,t)});if(p)return p}return Sf(e,t)};var uc=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},eo=new uc;eo.register("PersonaArtifactCard",Tf);function Sx(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Ef(e,t){var je,K,Y,ke;let n=(K=(je=e.features)==null?void 0:je.artifacts)==null?void 0:K.layout,o=((Y=n==null?void 0:n.toolbarPreset)!=null?Y:"default")==="document",s=(ke=n==null?void 0:n.panePadding)==null?void 0:ke.trim(),a=e.markdown?rs(e.markdown):null,i=Ps(e.sanitize),d=X=>{let ce=a?a(X):Br(X);return i?i(ce):ce},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let u=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let b=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");b.type="button",b.textContent="Close",b.setAttribute("aria-label","Close artifacts panel"),b.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let v="rendered",T=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),P=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),I=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,L=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(L&&C&&C.length>0),U=null,j,W=null,O=null;if(o&&(M||L)&&!R){if(j=M?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let X=he("chevron-down",14,"currentColor",2);X&&j.appendChild(X)}}else o&&R?(U=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=M?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=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"}}),U.append(j,W)):o?j=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Gt({icon:"copy",label:"Copy"});let F=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),ee=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Me=()=>{var Ge,ft,Ht;let X=(Ge=Se.find(nt=>nt.id===oe))!=null?Ge:Se[Se.length-1],ce=(ft=X==null?void 0:X.id)!=null?ft:null,Re=(X==null?void 0:X.artifactType)==="markdown"&&(Ht=X.markdown)!=null?Ht:"",be=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:Re,jsonPayload:be,id:ce}},pe=async()=>{var Ge;let{markdown:X,jsonPayload:ce}=Me(),Re=(Ge=Se.find(ft=>ft.id===oe))!=null?Ge:Se[Se.length-1],be=(Re==null?void 0:Re.artifactType)==="markdown"?X:Re?ce:"";try{await navigator.clipboard.writeText(be)}catch{}};if(j.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&R){let{markdown:ce,jsonPayload:Re,id:be}=Me();try{await X({actionId:"primary",artifactId:be,markdown:ce,jsonPayload:Re})}catch{}return}await pe()}),W&&(C!=null&&C.length)){let X=()=>{var Re;return(Re=u.closest("[data-persona-root]"))!=null?Re:document.body},ce=()=>{O=No({items:C.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:be,jsonPayload:Ge,id:ft}=Me(),Ht=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ht?await Ht({actionId:Re,artifactId:ft,markdown:be,jsonPayload:Ge}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(be):Re==="json"||Re==="source"?await navigator.clipboard.writeText(Ge):await navigator.clipboard.writeText(be||Ge)}catch{}},anchor:U!=null?U:W,position:"bottom-right",portal:X()})};u.isConnected?ce():requestAnimationFrame(ce),W.addEventListener("click",Re=>{Re.stopPropagation(),O==null||O.toggle()})}F.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}ie()}),ee.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let te=()=>{o&&(E.setAttribute("aria-pressed",v==="rendered"?"true":"false"),P.setAttribute("aria-pressed",v==="source"?"true":"false"))};E.addEventListener("click",()=>{v="rendered",te(),ie()}),P.addEventListener("click",()=>{v="source",te(),ie()});let Pe=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),T.append(E,P),U?I.append(U,F,ee):I.append(j,F,ee),f.append(T,Pe,I),te()):(f.appendChild(g),f.appendChild(b)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Ie=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),re=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ie.style.paddingLeft=s,Ie.style.paddingRight=s,re.style.padding=s),u.appendChild(f),u.appendChild(Ie),u.appendChild(re);let Se=[],oe=null,ae=!1,ie=()=>{var be,Ge,ft,Ht;let X=o&&Se.length<=1;Ie.classList.toggle("persona-hidden",X),Ie.replaceChildren();for(let nt of Se){let fe=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");fe.type="button",fe.textContent=nt.title||nt.id.slice(0,8),nt.id===oe&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(nt.id)),Ie.appendChild(fe)}re.replaceChildren();let ce=oe&&Se.find(nt=>nt.id===oe)||Se[Se.length-1];if(!ce)return;if(o){let nt=ce.artifactType==="markdown"?"MD":(be=ce.component)!=null?be:"Component",Q=(ce.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Pe.textContent=`${Q} \xB7 ${nt}`}else g.textContent="Artifacts";if(ce.artifactType==="markdown"){if(o&&v==="source"){let fe=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(Ge=ce.markdown)!=null?Ge:"",re.appendChild(fe);return}let nt=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");nt.innerHTML=d((ft=ce.markdown)!=null?ft:""),re.appendChild(nt);return}let Re=ce.component?eo.get(ce.component):void 0;if(Re){let fe={message:{id:ce.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Q=Re((Ht=ce.props)!=null?Ht:{},fe);if(Q){re.appendChild(Q);return}}catch{}}re.appendChild(Sx(ce))},ye=()=>{var ce;let X=Se.length>0;if(u.classList.toggle("persona-hidden",!X),c){let Re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ge=((ce=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ce:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&Ge&&ae?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(X){var ce,Re,be;Se=X.artifacts,oe=(be=(Re=X.selectedId)!=null?Re:(ce=X.artifacts[X.artifacts.length-1])==null?void 0:ce.id)!=null?be:null,Se.length>0&&(ae=!0),ie(),ye()},setMobileOpen(X){ae=X,!X&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ye()}}}function sr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Mf(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!sr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Tx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ki(e,t){var d,c,p,u,f,g,b,v,T,E;if(!sr(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"),Tx(e),Mf(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(b=n==null?void 0:n.panePadding)==null?void 0:b.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(T=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Mf(e,t)}var kf=["panel","seamless"];function Gi(e,t){var i,d,c,p,u,f;for(let g of kf)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!sr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=kf.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Lf(e,t){var n,r,o;return!t||!sr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Ex(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Mx(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function kx(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Lx(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Pf(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function If(e,t,n,r,o,s){let a=Ex(o,200),i=Lx(t,n,r,200);i=Math.max(a,i);let d=Mx(s);return d!==null&&(i=Math.min(i,d)),kx(e,a,i)}var Rf={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"}},mc=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,v,T;if(s.dataset.enhanced==="true")return;let a=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let i=(v=Rf[a])!=null?v:Rf.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let E=y("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var C,R;let P=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");P.htmlFor=`${t.id}-${a}-${E.name}`;let I=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=E.label,P.appendChild(I);let M=(C=E.type)!=null?C:"text",L;M==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=M),L.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",L.id=`${t.id}-${a}-${E.name}`,L.name=E.name,L.placeholder=(R=E.placeholder)!=null?R:"",E.required&&(L.required=!0),P.appendChild(L),p.appendChild(P)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(T=i.submitLabel)!=null?T:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async E=>{var L,C;E.preventDefault();let P=(L=n.formEndpoint)!=null?L:"/form",I=new FormData(p),M={};I.forEach((R,U)=>{M[U]=R}),M.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let U=await R.json();f.textContent=(C=U.message)!=null?C:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await r.sendMessage(String(U.nextPrompt))}catch(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var gc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Fa=new gc;var Wf=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Px=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ix=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},_a=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Px(e),n=Ix(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},fc=e=>typeof e=="string"?e:e==null?"":String(e),gs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:fc(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=fc(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:fc(n.text)}}},Hf=e=>Array.isArray(e)?e.map(t=>String(t)):[],$a=e=>{let t=new Set(Hf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Hf(e.getSessionMetadata().processedActionMessageIds))},r=()=>{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!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Rx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Wx=e=>e.map(t=>({...t,streaming:!1})),Hx=e=>e.map(t=>({...t,status:"complete"})),Ji=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Rx(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Wx(n.messages):void 0,artifacts:n.artifacts?Hx(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Js=require("partial-json");function Bx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Dx(e,t){if(!Bx(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 Xi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=(0,Js.parse)(n,Js.STR|Js.OBJ),s=Dx(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Bf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Qi(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=eo.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:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Df(){let e=Xi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Nf(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 Yi(e){let t=Nf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Zi(e){let t=Nf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Nx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function el(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Nx}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=r,g.appendChild(b);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,g.appendChild(v),f.appendChild(g);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let C=1;C<=5;C++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),R.title=c[C-1],R.dataset.rating=String(C),R.innerHTML=`
27
+ `,n.addEventListener("click",t);let r=s=>{var H,W,I,T,B,q,U,L,F,_,ee,Me,pe;let a=(H=s.launcher)!=null?H:{},i=rn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let te=(W=a.title)!=null?W:"Chat Assistant";d.textContent=te,d.setAttribute("title",te)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let te=(I=a.subtitle)!=null?I:"Here to help you get answers fast";c.textContent=te,c.setAttribute("title",te)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let te=(T=a.agentIconSize)!=null?T:"40px";if(u.style.height=te,u.style.width=te,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 Pe=parseFloat(te)||24,Ie=he(a.agentIconName,Pe*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(u.appendChild(Ie),u.style.display=""):(u.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(q=a.agentIconText)!=null?q:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let te=(U=a.agentIconSize)!=null?U:"40px";f.style.height=te,f.style.width=te,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let te=(L=a.callToActionIconSize)!=null?L:"32px";g.style.height=te,g.style.width=te,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Pe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Pe=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Ie=parseFloat(te)||24,re=Math.max(Ie-Pe,8),Se=he(a.callToActionIconName,re,"currentColor",2);Se?g.appendChild(Se):g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else g.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}let y=a.position&&br[a.position]?br[a.position]:br["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="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?S:`${v} ${y}`,i||(n.style.zIndex=String((ee=a.zIndex)!=null?ee:Cn));let E="1px solid var(--persona-border, #e5e7eb)",P="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=(Me=a.border)!=null?Me:E,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:P,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=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var yf=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=ff(e),s=hf(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={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:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},cc=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>lc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=lc(e,n);return{instance:o,element:o.element}};var qb=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}},zb=(e,t)=>{if(!e)return null;let n=qb(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Vb=(e,t)=>{let n=b("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},Kb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},dc=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(":"))},pc=320,xf=320,Gb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Jb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Xb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Qb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Yb=(e,t,n)=>{if(e.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let c=b("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${pc}px`,c.style.maxHeight=`${xf}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,c.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{p=!0}),Kb(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Zb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!dc(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${pc}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ex=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!dc(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${pc}px`,o.style.maxHeight=`${xf}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},tx=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!dc(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},us=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},uc=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:us};if(t){let o=t(r);if(o!==null)return o}return us()},nx=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},bf=(e,t,n="div")=>{let r=b(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},rx=(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},mc=(e,t,n)=>{var y,v,S,E,P,H,W;let r=(y=t.showCopy)!=null?y:!0,o=(v=t.showUpvote)!=null?v:!0,s=(S=t.showDownvote)!=null?S:!0,a=(E=t.showReadAloud)!=null?E:!1;if(!r&&!o&&!s&&!a){let I=b("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let i=(P=t.visibility)!=null?P:"hover",d=(H=t.align)!=null?H:"right",c=(W=t.layout)!=null?W:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(I,T,B)=>{let q=Gt({icon:I,label:T,size:14,className:"persona-message-action-btn"});return q.setAttribute("data-action",B),q};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Js=(e,t,n,r,o,s)=>{var oe,ae,ie,ye,je,K,Y,ke,X,ce,Re,be,Ge,ft,Ht,nt,fe;let a=n!=null?n:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,p=(ae=d==null?void 0:d.show)!=null?ae:!1,u=(ie=c==null?void 0:c.show)!=null?ie:!1,f=(ye=d==null?void 0:d.position)!=null?ye:"left",g=(je=c==null?void 0:c.position)!=null?je:"below",y=rx(e.role,i),v=b("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Gb(e),E=(Y=(K=e.content)==null?void 0:K.trim())!=null?Y:"",H=S.length>0&&E===xi,W=Bi((X=(ke=s==null?void 0:s.widgetConfig)==null?void 0:ke.features)==null?void 0:X.streamAnimation),I=(be=(Re=(ce=s==null?void 0:s.widgetConfig)==null?void 0:ce.features)==null?void 0:Re.streamAnimation)==null?void 0:be.plugins,T=e.role==="assistant"&&W.type!=="none"?Vs(W.type,I):null,B=e.role==="assistant"&&((Ge=T==null?void 0:T.isAnimating)==null?void 0:Ge.call(T,e))===!0,q=e.role==="assistant"&&T!==null&&(!!e.streaming||B);q&&(T!=null&&T.bubbleClass)&&v.classList.add(T.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),q&&T&&(T.containerClass&&U.classList.add(T.containerClass),U.style.setProperty("--persona-stream-step",`${W.speed}ms`),U.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let L=q?Di((ft=e.content)!=null?ft:"",W.buffer,T,e,!!e.streaming):(Ht=e.content)!=null?Ht:"",F=t({text:L,message:e,streaming:!!e.streaming,raw:e.rawContent}),_=F;q&&(T==null?void 0:T.wrap)==="char"?_=Wa(F,"char",e.id,{skipTags:T.skipTags}):q&&(T==null?void 0:T.wrap)==="word"&&(_=Wa(F,"word",e.id,{skipTags:T.skipTags}));let ee=null;if(H?(ee=document.createElement("div"),ee.innerHTML=_,ee.style.display="none",U.appendChild(ee)):U.innerHTML=_,q&&(T!=null&&T.useCaret)&&!H&&E){let Q=Ni(),lt=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ke=lt[lt.length-1];if(Ke!=null&&Ke.parentNode)Ke.parentNode.insertBefore(Q,Ke.nextSibling);else{let Te=U.lastElementChild;Te?Te.appendChild(Q):U.appendChild(Q)}}if(u&&g==="inline"&&e.createdAt){let Q=bf(e,c,"span");Q.classList.add("persona-timestamp-inline");let lt=U.lastElementChild;lt?lt.appendChild(Q):U.appendChild(Q)}if(S.length>0){let Q=Yb(S,!H&&!!E,()=>{H&&ee&&(ee.style.display="")});Q?v.appendChild(Q):H&&ee&&(ee.style.display="")}let Me=Jb(e);if(Me.length>0){let Q=Zb(Me);Q&&v.appendChild(Q)}let pe=Xb(e);if(pe.length>0){let Q=ex(pe);Q&&v.appendChild(Q)}let te=Qb(e);if(te.length>0){let Q=tx(te);Q&&v.appendChild(Q)}if(v.appendChild(U),u&&g==="below"&&e.createdAt){let Q=bf(e,c);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let Pe=e.role==="assistant"?zb(e.stopReason,(fe=(nt=s==null?void 0:s.widgetConfig)==null?void 0:nt.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(L&&L.trim()),lt=W.placeholder==="skeleton",Ke=lt&&W.buffer==="line"&&Q;if(Q)Ke&&v.appendChild(Ha());else if(lt)v.appendChild(Ha());else{let Te=uc("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Te&&v.appendChild(Te)}}if(Pe&&e.stopReason&&!e.streaming&&(E||(U.style.display="none"),v.appendChild(Vb(e.stopReason,Pe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=mc(e,r,o);v.appendChild(Q)}if(!p||e.role==="system")return v;let re=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=nx(d,e.role);return f==="right"||f==="left"&&e.role==="user"?re.append(v,Se):re.append(Se,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),re},vf=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Js(e,t,n,r,o,s)};var Xs=new Set,ox=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sx=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
+ `):""},wf=(e,t)=>{let n=Xs.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=he(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},gc=(e,t)=>{var pe,te,Pe,Ie,re,Se,oe,ae,ie,ye,je;let n=e.reasoning,r=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(te=(pe=t==null?void 0:t.features)==null?void 0:pe.reasoningDisplay)!=null?te:{},s=o.expandable!==!1,a=s&&Xs.has(e.id),i=n.status!=="complete",d=sx(e,(Pe=o.previewMaxLines)!=null?Pe:3),c=b("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");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Ie=t==null?void 0:t.reasoning)!=null?Ie:{},y=String((re=n.startedAt)!=null?re:Date.now()),v=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",y),K.textContent=ui(n),K},S=(Se=g.renderCollapsedSummary)==null?void 0:Se.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ui(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(u.textContent=S,p.appendChild(u)):S instanceof HTMLElement?p.appendChild(S):(u.textContent=f,p.appendChild(u));let E=b("span","persona-text-xs persona-text-persona-primary");E.textContent=hg(n),p.appendChild(E);let P=(oe=o.loadingAnimation)!=null?oe:"none",H=g.activeTextTemplate,W=g.completeTextTemplate,I=i?H:W,T=S instanceof HTMLElement,B=(K,Y,ke)=>{let X=ke;for(let ce of Y){let Re=b("span","persona-tool-char");Re.style.setProperty("--char-index",String(X)),Re.textContent=ce===" "?"\xA0":ce,K.appendChild(Re),X++}return X},q=(K,Y)=>{u.textContent="";let ke=mi(K,""),X=0;for(let ce of ke){let Re=ce.styles.length>0?(()=>{let be=b("span",ce.styles.map(Ge=>`persona-tool-text-${Ge}`).join(" "));return u.appendChild(be),be})():u;if(ce.isDuration&&i)Re.appendChild(v());else{let be=ce.isDuration?ui(n):ce.text;Y?X=B(Re,be,X):Re.appendChild(document.createTextNode(be))}}};if(!T&&I)if(E.style.display="none",u.style.display="",i&&P!=="none"){let K=(ae=g.loadingAnimationDuration)!=null?ae:2e3;u.setAttribute("data-preserve-animation","true"),P==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),q(I,!1)):(u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),P==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),q(I,!0))}else q(I,!1);else if(!T&&i&&P!=="none"){u.style.display="";let K=(ie=g.loadingAnimationDuration)!=null?ie:2e3;if(u.setAttribute("data-preserve-animation","true"),P==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),P==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Y=u.textContent||f;u.textContent="",B(u,Y,0)}n.status==="complete"&&(u.style.display="none")}else T||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(s){U=b("div","persona-flex persona-items-center");let Y=he(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?U.appendChild(Y):U.textContent=a?"Hide":"Show";let ke=b("div","persona-flex persona-items-center persona-ml-auto");ke.append(U),c.append(p,ke)}else c.append(p);let L=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(L.setAttribute("data-persona-collapsed-preview","reasoning"),L.style.display="none",L.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(je=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:je.call(ye,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});ox(L,K)||(L.textContent=d),L.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,L),r;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let _=n.chunks.join(""),ee=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ee.textContent=_||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(ee),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Y=he(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?U.appendChild(Y):U.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",L.style.display=a?"none":L.textContent||L.childNodes.length?"":"none"})(),r.append(c,L,F),r};var Qs=new Set,ax=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ix=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
+ `);let o=Po(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
+ `):""},fc=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},lx=(e,t)=>{var p,u,f,g,y;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=ix(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?yg(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return o==="tool-name"?c=((y=n.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ql(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ql(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Cf=(e,t,n)=>{var p;let r=Qs.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},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",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",f=he(r?"chevron-up":"chevron-down",16,u,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},hc=(e,t)=>{var _,ee,Me,pe,te,Pe,Ie,re,Se;let n=e.toolCall,r=(_=t==null?void 0:t.toolCall)!=null?_:{},o=b("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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Me=(ee=t==null?void 0:t.features)==null?void 0:ee.toolCallDisplay)!=null?Me:{},a=s.expandable!==!1,i=a&&Qs.has(e.id),{summary:d,previewText:c,isActive:p}=lx(e,t),u=b("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"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let y=String((pe=n.startedAt)!=null?pe:Date.now()),v=()=>{let oe=b("span","");return oe.setAttribute("data-tool-elapsed",y),oe.textContent=Aa(n),oe},S=(Pe=r.renderCollapsedSummary)==null?void 0:Pe.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(te=s.collapsedMode)!=null?te:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Aa(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(g.textContent=S,f.appendChild(g)):S instanceof HTMLElement?f.appendChild(S):(g.textContent=d,f.appendChild(g));let E=(Ie=s.loadingAnimation)!=null?Ie:"none",P=r.activeTextTemplate,H=r.completeTextTemplate,W=p?P:H,I=S instanceof HTMLElement,T=(oe,ae,ie)=>{let ye=ie;for(let je of ae){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(ye)),K.textContent=je===" "?"\xA0":je,oe.appendChild(K),ye++}return ye},B=(oe,ae)=>{var K;g.textContent="";let ie=((K=n.name)==null?void 0:K.trim())||"tool",ye=mi(oe,ie),je=0;for(let Y of ye){let ke=Y.styles.length>0?(()=>{let X=b("span",Y.styles.map(ce=>`persona-tool-text-${ce}`).join(" "));return g.appendChild(X),X})():g;if(Y.isDuration&&p)ke.appendChild(v());else{let X=Y.isDuration?Aa(n):Y.text;ae?je=T(ke,X,je):ke.appendChild(document.createTextNode(X))}}};if(!I)if(p&&E!=="none"){let oe=(re=r.loadingAnimationDuration)!=null?re:2e3;if(g.setAttribute("data-preserve-animation","true"),E==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),W&&B(W,!1);else if(g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),W)B(W,!0);else{let ae=g.textContent||d;g.textContent="",T(g,ae,0)}}else W&&B(W,!1);let q=null;if(a){q=b("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=he(i?"chevron-up":"chevron-down",16,oe,2);ae?q.appendChild(ae):q.textContent=i?"Hide":"Show";let ie=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(q),u.append(f,ie)}else u.append(f);let U=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let oe=(Se=r.renderCollapsedPreview)==null?void 0:Se.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});ax(U,oe)||(U.textContent=c),U.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,U),o;let L=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",r.contentBackgroundColor&&(L.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(L.style.color=r.contentTextColor),r.contentPaddingX&&(L.style.paddingLeft=r.contentPaddingX,L.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(L.style.paddingTop=r.contentPaddingY,L.style.paddingBottom=r.contentPaddingY),n.name){let oe=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=n.name,L.appendChild(oe)}if(n.args!==void 0){let oe=b("div","persona-space-y-1"),ae=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Arguments";let ie=b("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",fc(ie,r),ie.textContent=Po(n.args),oe.append(ae,ie),L.appendChild(oe)}if(n.chunks&&n.chunks.length){let oe=b("div","persona-space-y-1"),ae=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Activity";let ie=b("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",fc(ie,r),ie.textContent=n.chunks.join(""),oe.append(ae,ie),L.appendChild(oe)}if(n.status==="complete"&&n.result!==void 0){let oe=b("div","persona-space-y-1"),ae=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Result";let ie=b("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",fc(ie,r),ie.textContent=Po(n.result),oe.append(ae,ie),L.appendChild(oe)}if(n.status==="complete"&&typeof n.duration=="number"){let oe=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${n.duration}ms`,L.appendChild(oe)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),q){q.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=he(i?"chevron-up":"chevron-down",16,oe,2);ae?q.appendChild(ae):q.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(u,U,L),o};var ms=new Map,Ji=e=>{let n=(e.startsWith(hr)?e.slice(hr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Af=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Sf=(e,t)=>{var r,o,s;let n=(o=(r=Af(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ms.get(e))!=null?s:n==="expanded"},Tf=(e,t,n)=>{var a,i;let r=Af(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=he(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Ef=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Sf(e,n);Tf(r,s,n),o.style.display=s?"":"none"};var Xi=(e,t)=>{var B,q,U,L,F,_,ee,Me,pe,te,Pe,Ie,re,Se,oe;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=b("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=(B=r==null?void 0:r.backgroundColor)!=null?B:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(q=r==null?void 0:r.borderColor)!=null?q:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(U=r==null?void 0:r.titleColor)!=null?U:"currentColor",p=he(d,20,c,2);p&&i.appendChild(p);let u=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!o){let ae=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ae.setAttribute("data-approval-status",n.status),n.status==="approved"?(ae.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ae.style.color="var(--persona-palette-colors-success-700, #15803d)",ae.textContent="Approved"):n.status==="denied"?(ae.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ae.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ae.textContent="Denied"):n.status==="timeout"&&(ae.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ae.style.color="var(--persona-palette-colors-warning-700, #b45309)",ae.textContent="Timeout"),f.appendChild(ae)}u.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(hr)?ha(n.toolName):void 0,S=(F=r==null?void 0:r.formatDescription)==null?void 0:F.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),E=!n.toolName,P=S||(E?n.description:`The assistant wants to use \u201C${v!=null?v:Ji(n.toolName)}\u201D.`),H=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(H.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(H.style.color=r.descriptionColor),H.textContent=P,u.appendChild(H),n.reason){let ae=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ae.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?ae.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let ie=b("span","persona-font-medium");ie.textContent=`${(_=r==null?void 0:r.reasonLabel)!=null?_:"Agent's stated reason:"} `,ae.appendChild(ie),ae.appendChild(document.createTextNode(n.reason)),u.appendChild(ae)}let W=(ee=r==null?void 0:r.detailsDisplay)!=null?ee:"collapsed",I=!!n.description&&!E,T=I||!!n.parameters;if(W!=="hidden"&&T){let ae=Sf(e.id,t),ie=b("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");ie.type="button",ie.setAttribute("data-expand-header","true"),ie.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let ye=b("span");ye.setAttribute("data-approval-details-label","true");let je=b("span","persona-inline-flex persona-items-center");je.setAttribute("data-approval-details-chevron","true"),ie.append(ye,je),Tf(ie,ae,t),u.appendChild(ie);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=ae?"":"none",I){let Y=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Y.style.color=r.descriptionColor),Y.textContent=n.description,K.appendChild(Y)}if(n.parameters){let Y=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(Y.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Y.style.color=r.parameterTextColor),Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Y.textContent=Po(n.parameters),K.appendChild(Y)}u.appendChild(K)}if(o){let ae=b("div","persona-flex persona-gap-2 persona-mt-2");ae.setAttribute("data-approval-buttons","true");let ie=b("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");ie.type="button",ie.style.backgroundColor=(Me=r==null?void 0:r.approveButtonColor)!=null?Me:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",ie.setAttribute("data-approval-action","approve");let ye=he("shield-check",14,(te=r==null?void 0:r.approveButtonTextColor)!=null?te:"#ffffff",2);ye&&(ye.style.marginRight="4px",ie.appendChild(ye));let je=document.createTextNode((Pe=r==null?void 0:r.approveLabel)!=null?Pe:"Approve");ie.appendChild(je);let K=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ie=r==null?void 0:r.denyButtonColor)!=null?Ie:"transparent",K.style.color=(re=r==null?void 0:r.denyButtonTextColor)!=null?re:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let Y=he("shield-x",14,(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",2);Y&&(Y.style.marginRight="4px",K.appendChild(Y));let ke=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");K.appendChild(ke),ae.append(ie,K),u.appendChild(ae)}return a.append(i,u),s.appendChild(a),s};function cx(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Mf(e){var v;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,c=(v=e.container)!=null?v:cx(t),p=!1,u=null,f=()=>{if(!p)return;let S=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${S.width}px`);let E=r==="top-start"||r==="top-end"?S.top-o-n.getBoundingClientRect().height:S.bottom+o,P=r==="bottom-end"||r==="top-end"?S.right-n.getBoundingClientRect().width:S.left;n.style.top=`${E}px`,n.style.left=`${P}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},y=()=>{var I,T,B;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),f();let S=(T=((I=t.ownerDocument)!=null?I:document).defaultView)!=null?T:window,E=(B=t.ownerDocument)!=null?B:document,P=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},H=q=>{let U=typeof q.composedPath=="function"?q.composedPath():[];U.includes(n)||U.includes(t)||(g(),d==null||d("outside"))},W=S.setTimeout(()=>{E.addEventListener("pointerdown",H,!0)},0);S.addEventListener("scroll",P,!0),S.addEventListener("resize",P),u=()=>{S.clearTimeout(W),E.removeEventListener("pointerdown",H,!0),S.removeEventListener("scroll",P,!0),S.removeEventListener("resize",P)},i==null||i()};return{get isOpen(){return p},open:y,close:g,toggle:()=>p?g():y(),reposition:f,destroy:g}}function kf(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var dx=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Lf=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},gs=(e,t)=>{Lf(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)},px=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,ux=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ms.get(e))!=null?o:n==="expanded"},yc=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},mx=(e,t)=>{var c,p;let n=b("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(hr)?ha(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(c=e.description)!=null?c:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:Ji(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},gx=e=>{let t=b("div","persona-approval-resolved"),n=he("ban",15,"currentColor",2);n&&t.appendChild(n);let r=b("span","persona-approval-resolved-name");return r.textContent=e.toolName?Ji(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},fx=(e,t,n,r,o,s,a)=>{var q,U,L,F,_,ee,Me;let i=b("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"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(q=r==null?void 0:r.detailsDisplay)!=null?q:"collapsed",c=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=c||p,f=u&&ux(t.id,r),g=(U=r==null?void 0:r.showDetailsLabel)!=null?U:"Show details",y=(L=r==null?void 0:r.hideDetailsLabel)!=null?L:"Hide details",v=b("button","persona-approval-head");v.type="button",u?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",f?"true":"false"),v.setAttribute("aria-label",f?y:g)):v.setAttribute("data-static","true");let S=b("span","persona-approval-logo"),E=he("shield-check",16,"currentColor",2);E&&S.appendChild(E),v.appendChild(S);let P=mx(n,r);if(u){let pe=b("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let te=he("chevron-down",14,"currentColor",2);te&&pe.appendChild(te),P.append(" "),P.appendChild(pe)}v.appendChild(P),i.appendChild(v);let H=b("div","persona-approval-body");if(u){let pe=b("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!f,c){let te=b("p","persona-approval-desc");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=n.description,pe.appendChild(te)}if(p){let te=b("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(te.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.textContent=Po(n.parameters),pe.appendChild(te)}H.appendChild(pe)}if(n.reason){let pe=b("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let te=b("span","persona-approval-reason-label");te.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,pe.append(te,document.createTextNode(n.reason)),H.appendChild(pe)}let W=b("div","persona-approval-actions"),I=null,T=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},B=b("button","persona-approval-deny");if(B.type="button",B.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(B.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(B.style.color=r.denyButtonTextColor),B.append((_=r==null?void 0:r.denyLabel)!=null?_:"Deny"),a){let pe=b("div","persona-approval-split"),te=b("button","persona-approval-primary");te.type="button",te.setAttribute("data-action","always"),T(te),te.append((ee=r==null?void 0:r.approveLabel)!=null?ee:"Always allow",yc("\u23CE"));let Pe=b("button","persona-approval-caret");Pe.type="button",Pe.setAttribute("data-action","toggle-menu"),Pe.setAttribute("aria-label","More options"),T(Pe);let Ie=he("chevron-down",15,"currentColor",2);Ie&&Pe.appendChild(Ie),pe.append(te,Pe),W.append(pe,B),B.append(yc("Esc"));let re=b("div","persona-approval-menu"),Se=b("button","persona-approval-menu-item");Se.type="button",Se.append("Allow once",yc("\u2318\u23CE")),re.appendChild(Se),I=Mf({anchor:pe,content:re,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,I),Se.addEventListener("click",()=>{gs(e,t.id),o()})}else{let pe=b("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),T(pe),pe.append((Me=r==null?void 0:r.approveLabel)!=null?Me:"Allow"),W.append(pe,B)}return H.appendChild(W),i.appendChild(H),i.addEventListener("click",pe=>{let te=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!te)return;let Pe=te.getAttribute("data-action");if(Pe==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let re=Ie.hidden;Ie.hidden=!re,v.setAttribute("aria-expanded",re?"true":"false"),v.setAttribute("aria-label",re?y:g),ms.set(t.id,re)}return}if(Pe==="toggle-menu"){I==null||I.toggle();return}if(Pe==="always"){gs(e,t.id),o({remember:!0});return}if(Pe==="allow"){gs(e,t.id),o();return}if(Pe==="deny"){gs(e,t.id),s();return}}),i},Pf=()=>{let e=dx();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=px(a);if(i.status!=="pending"){if(gs(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return gx(i)}Lf(e,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=fx(e,r,i,d,o,s,c);if(c){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=f=>{kf(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),gs(e,r.id),f.key==="Escape"?s():f.metaKey||f.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])gs(e,r);e.latestPendingApprovalId=null}}};var If=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(S=>S.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=y=>{switch(y){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(y=>{let v=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=y,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(v),t.push(v)}),e.appendChild(u),p){let y=JSON.stringify(o);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Fa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var _a=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}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(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var hx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),yx=new Set(["step_start","execution_start"]),bx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),xx=new Set(["step_complete","agent_turn_complete"]),vx=new Set(["flow_complete","agent_complete"]),Rf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fs=(e,t)=>{let n=e[t];return Hf(n)?n:void 0};function bc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Qi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function wx(e,t){return typeof t.type=="string"?t.type:e}function Cx(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 Ax(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 Wf(e){var r,o,s,a,i;let t=fs(e,"result"),n=[fs(e,"tokens"),fs(e,"totalTokens"),t?fs(t,"tokens"):void 0,fs(e,"usage"),t?fs(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=Kn(d.output))!=null?r:Kn(d.outputTokens))!=null?o:Kn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Kn(e.outputTokens))!=null?s:Kn(e.completionTokens))!=null?i:t?(a=Kn(t.outputTokens))!=null?a:Kn(t.completionTokens):void 0}function Sx(e){var n,r,o,s,a;let t=fs(e,"result");return(a=(o=(r=(n=Kn(e.executionTime))!=null?n:Kn(e.executionTimeMs))!=null?r:Kn(e.execution_time))!=null?o:Kn(e.duration))!=null?a:t?(s=Kn(t.executionTime))!=null?s:Kn(t.executionTimeMs):void 0}function Tx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var $a=class{constructor(t=Tx){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:Qi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!Hf(n)){Rf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=wx(t,n),o=this.now();if(hx.has(r)){this.startRun(o);return}if(yx.has(r)){this.run||this.startRun(o);return}if(bx.has(r)){if(!Ax(r,n))return;let a=Cx(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+bc(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Qi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(xx.has(r)){if(!this.run)return;let a=this.run,i=Wf(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+bc(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Qi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(vx.has(r)){if(!this.run)return;let a=this.run,i=Wf(n),d=i!=null?i:a.exactOutputTokens+bc(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Qi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(Rf.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Sx(n);return s!=null?s:r-t.startedAt}};function Ys(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Ex={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)"}},Mx={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},kx=["flowName","stepName","reasoningText","text","name","tool","toolName"],Lx=100;function Px(e,t){let n={...Ex,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Mx}function Ix(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Rx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function Wx(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)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 Hx(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function Bx(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 Dx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Nx(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 Ox(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function xc(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Ys(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){var _,ee;let g=b("div",""),y=b("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");y.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=he(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&v.appendChild(S);let E=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=(_=r.timestampFormat)!=null?_:"relative";E.textContent=P==="relative"?Ix(e.timestamp,n):Rx(e.timestamp);let H=null;r.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let W=Px(e.type,r.badgeColors),I=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");I.style.backgroundColor=W.bg,I.style.color=W.text,I.style.borderColor=W.text+"50",I.textContent=e.type;let T=(ee=r.descriptionFields)!=null?ee:kx,B=Wx(e.payload,T),q=null;B&&(q=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),q.textContent=B);let U=b("div","persona-flex-1 persona-min-w-0"),L=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),F=he("clipboard","12px","currentColor",1.5);return F&&L.appendChild(F),L.addEventListener("click",async Me=>{Me.stopPropagation(),await Hx(Bx(e)),L.innerHTML="";let pe=he("check","12px","currentColor",1.5);pe&&L.appendChild(pe),setTimeout(()=>{L.innerHTML="";let te=he("clipboard","12px","currentColor",1.5);te&&L.appendChild(te)},1500)}),y.appendChild(v),y.appendChild(E),H&&y.appendChild(H),y.appendChild(I),q&&y.appendChild(q),y.appendChild(U),y.appendChild(L),g.appendChild(y),d&&g.appendChild(Ox(e,a,i)),g}}function Bf(e){var y,v,S,E,P;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",u=(P=(E=o==null?void 0:o.features)==null?void 0:E.eventStream)!=null?P:{},f=s.find(H=>H.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let H=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return g();function g(){let H=u.classNames,W=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ys(W,H==null?void 0:H.panel);let I=[],T="",B="",q=null,U=[],L={},F=0,_=Ri(),ee=0,Me=0,pe=!1,te=null,Pe=!1,Ie=0,re=new Set,Se=new Map,oe="",ae="",ie=null,ye,je,K,Y,ke=null,X=null,ce=null;function Re(){let ge=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),D=b("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(Ys(D,H==null?void 0:H.headerBar),a){X=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),X.style.cursor="help",ke=b("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"),ke.textContent="-- tok/s",ce=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ce.style.display="none",ce.style.pointerEvents="none";let Ft=X,en=ce,wr=()=>{if(!en.textContent)return;let ar=Ft.getBoundingClientRect(),ir=ge.getBoundingClientRect();en.style.left=`${ar.left-ir.left}px`,en.style.top=`${ar.bottom-ir.top+4}px`,en.style.display="block"},Fr=()=>{en.style.display="none"};X.addEventListener("mouseenter",wr),X.addEventListener("mouseleave",Fr),X.appendChild(ke)}let ve=b("div","persona-flex-1");ye=b("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 de=b("option","");de.value="",de.textContent="All events (0)",ye.appendChild(de),je=b("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"),je.type="button",je.title="Copy All";let Xe=he("clipboard-copy","12px","currentColor",1.5);Xe&&je.appendChild(Xe);let Pt=b("span","persona-event-copy-all persona-text-xs");Pt.textContent="Copy All",je.appendChild(Pt),X&&D.appendChild(X),D.appendChild(ve),D.appendChild(ye),D.appendChild(je);let kt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ys(kt,H==null?void 0:H.searchBar);let vt=he("search","14px","var(--persona-muted, #9ca3af)",1.5),Wt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");vt&&Wt.appendChild(vt),K=b("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"),Ys(K,H==null?void 0:H.searchInput),K.type="text",K.placeholder="Search event payloads...",Y=b("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"),Y.type="button",Y.style.display="none";let Qt=he("x","12px","currentColor",2);return Qt&&Y.appendChild(Qt),kt.appendChild(Wt),kt.appendChild(K),kt.appendChild(Y),ge.appendChild(D),ge.appendChild(kt),ce&&ge.appendChild(ce),ge}let be,Ge=s.find(ge=>ge.renderEventStreamToolbar);if(Ge!=null&&Ge.renderEventStreamToolbar&&o){let ge=Ge.renderEventStreamToolbar({config:o,defaultRenderer:()=>Re(),eventCount:t.getSize(),filteredCount:0,onFilterChange:D=>{T=D,xe(),At()},onSearchChange:D=>{B=D,xe(),At()}});be=ge!=null?ge:Re()}else be=Re();let ft=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");ft.style.display="none";function Ht(){if(!a||!ke||!X)return;let ge=a(),D=Dx(ge);ke.textContent=D;let ve=Nx(ge);ce&&(ce.textContent=ve,ve||(ce.style.display="none")),X.setAttribute("aria-label",ve?`Throughput: ${D}, ${ve}`:`Throughput: ${D}`)}let nt=b("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.style.height="100%";let Q=b("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");Ys(Q,H==null?void 0:H.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let lt=he(c,"14px","currentColor",2);lt&&Q.appendChild(lt);let Ke=b("span","");Ke.textContent=p,Q.appendChild(Ke);let Te=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Te.style.display="none",nt.appendChild(fe),nt.appendChild(Te),nt.appendChild(Q),W.setAttribute("tabindex","0"),W.appendChild(be),W.appendChild(ft),W.appendChild(nt);function Ce(){let ge=t.getAll(),D={};for(let kt of ge)D[kt.type]=(D[kt.type]||0)+1;let ve=Object.keys(D).sort(),de=ve.length!==U.length||!ve.every((kt,vt)=>kt===U[vt]),ht=!de&&ve.some(kt=>D[kt]!==L[kt]),Xe=ge.length!==Object.values(L).reduce((kt,vt)=>kt+vt,0);if(!de&&!ht&&!Xe||(U=ve,L=D,!ye))return;let Pt=ye.value;if(ye.options[0].textContent=`All events (${ge.length})`,de){for(;ye.options.length>1;)ye.remove(1);for(let kt of ve){let vt=b("option","");vt.value=kt,vt.textContent=`${kt} (${D[kt]||0})`,ye.appendChild(vt)}Pt&&ve.includes(Pt)?ye.value=Pt:Pt&&(ye.value="",T="")}else for(let kt=1;kt<ye.options.length;kt++){let vt=ye.options[kt];vt.textContent=`${vt.value} (${D[vt.value]||0})`}}function et(){let ge=t.getAll();if(T&&(ge=ge.filter(D=>D.type===T)),B){let D=B.toLowerCase();ge=ge.filter(ve=>ve.type.toLowerCase().includes(D)||ve.payload.toLowerCase().includes(D))}return ge}function zt(){return T!==""||B!==""}function xe(){F=0,ee=0,_.resume(),Q.style.display="none"}function ue(ge){re.has(ge)?re.delete(ge):re.add(ge),ie=ge;let D=fe.scrollTop,ve=_.isFollowing();Pe=!0,_.pause(),At(),fe.scrollTop=D,ve&&_.resume(),Pe=!1}function An(){return Bo(fe,50)}function At(){Me=Date.now(),pe=!1,Ht(),Ce();let ge=t.getEvictedCount();ge>0?(ft.textContent=`${ge.toLocaleString()} older events truncated`,ft.style.display=""):ft.style.display="none",I=et();let D=I.length,ve=t.getSize()>0;D===0&&ve&&zt()?(Te.textContent=B?`No events matching '${B}'`:"No events matching filter",Te.style.display="",fe.style.display="none"):(Te.style.display="none",fe.style.display=""),je&&(je.title=zt()?`Copy Filtered (${D})`:"Copy All"),d&&!_.isFollowing()&&D>F&&(ee+=D-F,Ke.textContent=p?`${p}${ee>0?` (${ee})`:""}`:"",Q.style.display=""),F=D;let de=t.getAll(),ht=de.length>0?de[0].timestamp:0,Xe=new Set(I.map(vt=>vt.id));for(let vt of re)Xe.has(vt)||re.delete(vt);let Pt=T!==oe||B!==ae,kt=Se.size===0&&I.length>0;if(Pt||kt||I.length===0){fe.innerHTML="",Se.clear();let vt=document.createDocumentFragment();for(let Wt=0;Wt<I.length;Wt++){let Qt=xc(I[Wt],Wt,ht,u,re,ue,s,o);Se.set(I[Wt].id,Qt),vt.appendChild(Qt)}fe.appendChild(vt),oe=T,ae=B,ie=null}else{if(ie!==null){let Wt=Se.get(ie);if(Wt&&Wt.parentNode===fe){let Qt=I.findIndex(Ft=>Ft.id===ie);if(Qt>=0){let Ft=xc(I[Qt],Qt,ht,u,re,ue,s,o);fe.insertBefore(Ft,Wt),Wt.remove(),Se.set(ie,Ft)}}ie=null}let vt=new Set(I.map(Wt=>Wt.id));for(let[Wt,Qt]of Se)vt.has(Wt)||(Qt.remove(),Se.delete(Wt));for(let Wt=0;Wt<I.length;Wt++){let Qt=I[Wt];if(!Se.has(Qt.id)){let Ft=xc(Qt,Wt,ht,u,re,ue,s,o);Se.set(Qt.id,Ft),fe.appendChild(Ft)}}}_.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function bn(){if(Date.now()-Me>=Lx){te!==null&&(cancelAnimationFrame(te),te=null),At();return}pe||(pe=!0,te=requestAnimationFrame(()=>{te=null,At()}))}let xr=(ge,D)=>{if(!je)return;je.innerHTML="";let ve=he(ge,"12px","currentColor",1.5);ve&&je.appendChild(ve);let de=b("span","persona-text-xs");de.textContent="Copy All",je.appendChild(de),setTimeout(()=>{je.innerHTML="";let ht=he("clipboard-copy","12px","currentColor",1.5);ht&&je.appendChild(ht);let Xe=b("span","persona-text-xs");Xe.textContent="Copy All",je.appendChild(Xe),je.disabled=!1},D)},vr=async()=>{if(je){je.disabled=!0;try{let ge;zt()?ge=I:n?(ge=await n(),ge.length===0&&(ge=t.getAll())):ge=t.getAll();let D=ge.map(ve=>{try{return JSON.parse(ve.payload)}catch{return ve.payload}});await navigator.clipboard.writeText(JSON.stringify(D,null,2)),xr("check",1500)}catch{xr("x",1500)}}},qe=()=>{ye&&(T=ye.value,xe(),At())},M=()=>{!K||!Y||(Y.style.display=K.value?"":"none",q&&clearTimeout(q),q=setTimeout(()=>{B=K.value,xe(),At()},150))},me=()=>{!K||!Y||(K.value="",B="",Y.style.display="none",q&&clearTimeout(q),xe(),At())},Ee=()=>{if(Pe)return;let ge=fe.scrollTop,{action:D,nextLastScrollTop:ve}=Wi({following:_.isFollowing(),currentScrollTop:ge,lastScrollTop:Ie,nearBottom:An(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=ve,D==="resume"?(_.resume(),ee=0,Q.style.display="none"):D==="pause"&&(_.pause(),d&&(Ke.textContent=p,Q.style.display=""))},Le=ge=>{let D=Hi({following:_.isFollowing(),deltaY:ge.deltaY,nearBottom:An(),resumeWhenNearBottom:!0});D==="pause"?(_.pause(),d&&(Ke.textContent=p,Q.style.display="")):D==="resume"&&(_.resume(),ee=0,Q.style.display="none")},Be=()=>{d&&(fe.scrollTop=fe.scrollHeight,_.resume(),ee=0,Q.style.display="none")},rt=ge=>{let D=ge.target;if(!D||D.closest("button"))return;let ve=D.closest("[data-event-id]");if(!ve)return;let de=ve.getAttribute("data-event-id");de&&ue(de)},Ye=ge=>{if((ge.metaKey||ge.ctrlKey)&&ge.key==="f"){ge.preventDefault(),K==null||K.focus(),K==null||K.select();return}ge.key==="Escape"&&(K&&document.activeElement===K?(me(),K.blur(),W.focus()):r&&r())};je&&je.addEventListener("click",vr),ye&&ye.addEventListener("change",qe),K&&K.addEventListener("input",M),Y&&Y.addEventListener("click",me),fe.addEventListener("scroll",Ee),fe.addEventListener("wheel",Le,{passive:!0}),fe.addEventListener("click",rt),Q.addEventListener("click",Be),W.addEventListener("keydown",Ye);function yt(){q&&clearTimeout(q),te!==null&&(cancelAnimationFrame(te),te=null),pe=!1,Se.clear(),je&&je.removeEventListener("click",vr),ye&&ye.removeEventListener("change",qe),K&&K.removeEventListener("input",M),Y&&Y.removeEventListener("click",me),fe.removeEventListener("scroll",Ee),fe.removeEventListener("wheel",Le),fe.removeEventListener("click",rt),Q.removeEventListener("click",Be),W.removeEventListener("keydown",Ye)}return{element:W,update:bn,destroy:yt}}}function Df(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(c.append(p,u),i.append(d,c),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Nf=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Df(e,t)});if(p)return p}return Df(e,t)};var vc=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},ro=new vc;ro.register("PersonaArtifactCard",Nf);function Fx(e){var o;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Of(e,t){var je,K,Y,ke;let n=(K=(je=e.features)==null?void 0:je.artifacts)==null?void 0:K.layout,o=((Y=n==null?void 0:n.toolbarPreset)!=null?Y:"default")==="document",s=(ke=n==null?void 0:n.panePadding)==null?void 0:ke.trim(),a=e.markdown?ss(e.markdown):null,i=Ws(e.sanitize),d=X=>{let ce=a?a(X):Br(X);return i?i(ce):ce},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};c&&c.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let u=b("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");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=b("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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=b("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let y=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let v="rendered",S=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),P=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,T=n==null?void 0:n.documentToolbarCopyMenuItems,B=!!(I&&T&&T.length>0),q=null,U,L=null,F=null;if(o&&(W||I)&&!B){if(U=W?Na({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let X=he("chevron-down",14,"currentColor",2);X&&U.appendChild(X)}}else o&&B?(q=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),U=W?Na({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=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"}}),q.append(U,L)):o?U=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):U=Gt({icon:"copy",label:"Copy"});let _=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),ee=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Me=()=>{var Ge,ft,Ht;let X=(Ge=Se.find(nt=>nt.id===oe))!=null?Ge:Se[Se.length-1],ce=(ft=X==null?void 0:X.id)!=null?ft:null,Re=(X==null?void 0:X.artifactType)==="markdown"&&(Ht=X.markdown)!=null?Ht:"",be=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:Re,jsonPayload:be,id:ce}},pe=async()=>{var Ge;let{markdown:X,jsonPayload:ce}=Me(),Re=(Ge=Se.find(ft=>ft.id===oe))!=null?Ge:Se[Se.length-1],be=(Re==null?void 0:Re.artifactType)==="markdown"?X:Re?ce:"";try{await navigator.clipboard.writeText(be)}catch{}};if(U.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&B){let{markdown:ce,jsonPayload:Re,id:be}=Me();try{await X({actionId:"primary",artifactId:be,markdown:ce,jsonPayload:Re})}catch{}return}await pe()}),L&&(T!=null&&T.length)){let X=()=>{var Re;return(Re=u.closest("[data-persona-root]"))!=null?Re:document.body},ce=()=>{F=Fo({items:T.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:be,jsonPayload:Ge,id:ft}=Me(),Ht=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ht?await Ht({actionId:Re,artifactId:ft,markdown:be,jsonPayload:Ge}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(be):Re==="json"||Re==="source"?await navigator.clipboard.writeText(Ge):await navigator.clipboard.writeText(be||Ge)}catch{}},anchor:q!=null?q:L,position:"bottom-right",portal:X()})};u.isConnected?ce():requestAnimationFrame(ce),L.addEventListener("click",Re=>{Re.stopPropagation(),F==null||F.toggle()})}_.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}ie()}),ee.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let te=()=>{o&&(E.setAttribute("aria-pressed",v==="rendered"?"true":"false"),P.setAttribute("aria-pressed",v==="source"?"true":"false"))};E.addEventListener("click",()=>{v="rendered",te(),ie()}),P.addEventListener("click",()=>{v="source",te(),ie()});let Pe=b("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");o?(f.replaceChildren(),S.append(E,P),q?H.append(q,_,ee):H.append(U,_,ee),f.append(S,Pe,H),te()):(f.appendChild(g),f.appendChild(y)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Ie=b("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"),re=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ie.style.paddingLeft=s,Ie.style.paddingRight=s,re.style.padding=s),u.appendChild(f),u.appendChild(Ie),u.appendChild(re);let Se=[],oe=null,ae=!1,ie=()=>{var be,Ge,ft,Ht;let X=o&&Se.length<=1;Ie.classList.toggle("persona-hidden",X),Ie.replaceChildren();for(let nt of Se){let fe=b("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");fe.type="button",fe.textContent=nt.title||nt.id.slice(0,8),nt.id===oe&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(nt.id)),Ie.appendChild(fe)}re.replaceChildren();let ce=oe&&Se.find(nt=>nt.id===oe)||Se[Se.length-1];if(!ce)return;if(o){let nt=ce.artifactType==="markdown"?"MD":(be=ce.component)!=null?be:"Component",Q=(ce.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Pe.textContent=`${Q} \xB7 ${nt}`}else g.textContent="Artifacts";if(ce.artifactType==="markdown"){if(o&&v==="source"){let fe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(Ge=ce.markdown)!=null?Ge:"",re.appendChild(fe);return}let nt=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");nt.innerHTML=d((ft=ce.markdown)!=null?ft:""),re.appendChild(nt);return}let Re=ce.component?ro.get(ce.component):void 0;if(Re){let fe={message:{id:ce.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Q=Re((Ht=ce.props)!=null?Ht:{},fe);if(Q){re.appendChild(Q);return}}catch{}}re.appendChild(Fx(ce))},ye=()=>{var ce;let X=Se.length>0;if(u.classList.toggle("persona-hidden",!X),c){let Re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ge=((ce=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ce:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&Ge&&ae?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(X){var ce,Re,be;Se=X.artifacts,oe=(be=(Re=X.selectedId)!=null?Re:(ce=X.artifacts[X.artifacts.length-1])==null?void 0:ce.id)!=null?be:null,Se.length>0&&(ae=!0),ie(),ye()},setMobileOpen(X){ae=X,!X&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ye()}}}function sr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Ff(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!sr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function _x(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Yi(e,t){var d,c,p,u,f,g,y,v,S,E;if(!sr(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"),_x(e),Ff(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(y=n==null?void 0:n.panePadding)==null?void 0:y.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ff(e,t)}var _f=["panel","seamless"];function Zi(e,t){var i,d,c,p,u,f;for(let g of _f)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!sr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=_f.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function $f(e,t){var n,r,o;return!t||!sr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function $x(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function jx(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Ux(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function qx(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function jf(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Uf(e,t,n,r,o,s){let a=$x(o,200),i=qx(t,n,r,200);i=Math.max(a,i);let d=jx(s);return d!==null&&(i=Math.min(i,d)),Ux(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"}},wc=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,v,S;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(v=qf[a])!=null?v:qf.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let E=b("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var T,B;let P=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");P.htmlFor=`${t.id}-${a}-${E.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=E.label,P.appendChild(H);let W=(T=E.type)!=null?T:"text",I;W==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=W),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}-${E.name}`,I.name=E.name,I.placeholder=(B=E.placeholder)!=null?B:"",E.required&&(I.required=!0),P.appendChild(I),p.appendChild(P)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(S=i.submitLabel)!=null?S:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async E=>{var I,T;E.preventDefault();let P=(I=n.formEndpoint)!=null?I:"/form",H=new FormData(p),W={};H.forEach((B,q)=>{W[q]=B}),W.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let B=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!B.ok)throw new Error(`Form submission failed (${B.status})`);let q=await B.json();f.textContent=(T=q.message)!=null?T:"Thanks! We'll be in touch soon.",q.success&&q.nextPrompt&&await r.sendMessage(String(q.nextPrompt))}catch(B){f.textContent=B instanceof Error?B.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Cc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},ja=new Cc;var zf=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var zx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Vx=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ua=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=zx(e),n=Vx(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Ac=e=>typeof e=="string"?e:e==null?"":String(e),hs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ac(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Ac(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Ac(n.text)}}},Vf=e=>Array.isArray(e)?e.map(t=>String(t)):[],qa=e=>{let t=new Set(Vf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Vf(e.getSessionMetadata().processedActionMessageIds))},r=()=>{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!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Kx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Gx=e=>e.map(t=>({...t,streaming:!1})),Jx=e=>e.map(t=>({...t,status:"complete"})),el=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Kx(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Gx(n.messages):void 0,artifacts:n.artifacts?Jx(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Zs=require("partial-json");function Xx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Qx(e,t){if(!Xx(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 tl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=(0,Zs.parse)(n,Zs.STR|Zs.OBJ),s=Qx(o,n);s&&(e=s)}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 nl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=ro.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:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Gf(){let e=tl();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 za(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 rl(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 r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Yx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ol(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Yx}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=r,g.appendChild(y);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,g.appendChild(v),f.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let T=1;T<=5;T++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${T} star${T>1?"s":""}: ${c[T-1]}`),B.title=c[T-1],B.dataset.rating=String(T),B.innerHTML=`
31
31
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
32
32
  <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>
33
33
  </svg>
34
- `,R.addEventListener("click",()=>{u=C,E.forEach((U,j)=>{let W=j<C;U.classList.toggle("selected",W),U.setAttribute("aria-checked",j===C-1?"true":"false")})}),E.push(R),T.appendChild(R)}f.appendChild(T);let P=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),C.appendChild(P),f.appendChild(C)}let I=document.createElement("div");I.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{n==null||n(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(u===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let C=(P==null?void 0:P.value.trim())||void 0;await t(u,C),p.remove()}catch(C){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(M),I.appendChild(L),f.appendChild(I),p.appendChild(f),p}function tl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,b.appendChild(v);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=o,b.appendChild(T),g.appendChild(b);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=p,P.appendChild(I),P.appendChild(M);let L=document.createElement("div");L.className="persona-feedback-numbers";let C=[];for(let O=0;O<=10;O++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-number-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`Rating ${O} out of 10`),F.textContent=String(O),F.dataset.rating=String(O),O<=6?F.classList.add("persona-feedback-detractor"):O<=8?F.classList.add("persona-feedback-passive"):F.classList.add("persona-feedback-promoter"),F.addEventListener("click",()=>{f=O,C.forEach((ee,Me)=>{ee.classList.toggle("selected",Me===O),ee.setAttribute("aria-checked",Me===O?"true":"false")})}),C.push(F),L.appendChild(F)}E.appendChild(P),E.appendChild(L),g.appendChild(E);let R=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),O.appendChild(R),g.appendChild(O)}let U=document.createElement("div");U.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=i,j.addEventListener("click",()=>{n==null||n(),u.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let O=(R==null?void 0:R.value.trim())||void 0;await t(f,O),u.remove()}catch(O){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),U.appendChild(j),U.appendChild(W),g.appendChild(U),u.appendChild(g),u}var Xs="persona-chat-history",Ox=30*1e3,Fx={"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 _x(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Fx[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function nl(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 $x(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function jx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var hc=e=>!e||typeof e!="object"?{}:{...e},Of=e=>e.map(t=>({...t,streaming:!1})),Ff=(e,t,n)=>{let r=e!=null&&e.markdown?rs(e.markdown):null,o=Ps(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=ns()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});c=o?o(g):g}else if(r){let g=s.streaming?Nm(a):a,b=r(g);c=o&&d?o(b):b}else c=Br(a);return c}};function _f(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=he(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var rl=(e,t,n)=>{var hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=wi(t),o=Fa.getForInstance(r.plugins),{plugin:s,teardown:a}=bf();r.components&&eo.registerAll(r.components);let i=Wf(),c=r.persistState===!1?null:(hd=r.storageAdapter)!=null?hd:Ji(),p={},u=null,f=!1,g=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:x}=m;return x&&(f=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")u=l.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=l!=null?l:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=hc(h.metadata)),(yd=h.messages)!=null&&yd.length&&(r={...r,initialMessages:h.messages}),(bd=h.artifacts)!=null&&bd.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(xd=h.selectedArtifactId)!=null?xd:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=g({messages:[],metadata:{}});(vd=l.messages)!=null&&vd.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let b=()=>p,v=l=>{var h;p=(h=l({...p}))!=null?h:{},In()},T=r.actionParsers&&r.actionParsers.length?r.actionParsers:[_a],E=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[gs.message,gs.messageAndClick],P=$a({parsers:T,handlers:E,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});P.syncFromMetadata();let I=(Cd=(wd=r.launcher)==null?void 0:wd.enabled)!=null?Cd:!0,M=(Sd=(Ad=r.launcher)==null?void 0:Ad.autoExpand)!=null?Sd:!1,L=(Td=r.autoFocusInput)!=null?Td:!1,C=M,R=I,U=(Md=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Md.layout,j=!1,W=()=>Do(r),O=()=>I||W(),F=W()?!1:I?M:!0,ee=!1,Me=null,pe=()=>{ee=!0,Me&&clearTimeout(Me),Me=setTimeout(()=>{ee&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ee=!1)},1e4)},te=Ff(r,P,pe),Pe=(Ld=(kd=r.features)==null?void 0:kd.showReasoning)!=null?Ld:!0,Ie=(Id=(Pd=r.features)==null?void 0:Pd.showToolCalls)!=null?Id:!0,re=(Wd=(Rd=r.features)==null?void 0:Rd.showEventStreamToggle)!=null?Wd:!1,Se=(Bd=(Hd=r.features)==null?void 0:Hd.scrollToBottom)!=null?Bd:{},oe=(Nd=(Dd=r.features)==null?void 0:Dd.scrollBehavior)!=null?Nd:{},ie=`${(Fd=typeof r.persistState=="object"?(Od=r.persistState)==null?void 0:Od.keyPrefix:void 0)!=null?Fd:"persona-"}event-stream`,ye=re?new Na(ie):null,je=(jd=($d=(_d=r.features)==null?void 0:_d.eventStream)==null?void 0:$d.maxEvents)!=null?jd:2e3,K=re?new Da(je,ye):null,Y=re?new Oa:null,ke=null,X=!1,ce=null,Re=0;ye==null||ye.open().then(()=>K==null?void 0:K.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let be={onCopy:l=>{var m,h;i.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,l)},onFeedback:l=>{var m,h;i.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,l)}},Ge=(Ud=r.statusIndicator)!=null?Ud:{},ft=l=>{var m,h,x,S,H,q;return l==="idle"?(m=Ge.idleText)!=null?m:rn.idle:l==="connecting"?(h=Ge.connectingText)!=null?h:rn.connecting:l==="connected"?(x=Ge.connectedText)!=null?x:rn.connected:l==="error"?(S=Ge.errorText)!=null?S:rn.error:l==="paused"?(H=Ge.pausedText)!=null?H:rn.paused:l==="resuming"?(q=Ge.resumingText)!=null?q:rn.resuming:rn[l]};function Ht(l,m,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=m,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=m}let nt=of({config:r,showClose:O()}),{wrapper:fe,panel:Q,pillRoot:lt}=nt.shell,Ke=nt.panelElements,{container:Te,body:Ce,messagesWrapper:et,suggestions:zt,textarea:xe,sendButton:ue,sendButtonWrapper:wn,composerForm:At,statusText:hn,introTitle:vr,introSubtitle:wr,closeButton:qe,iconHolder:k,headerTitle:me,headerSubtitle:Ee,header:Le,footer:Be,actionsRow:rt,leftActions:Ye,rightActions:yt}=Ke,ge=Ke.setSendButtonMode,D=Ke.micButton,ve=Ke.micButtonWrapper,de=Ke.attachmentButton,ht=Ke.attachmentButtonWrapper,Xe=Ke.attachmentInput,Pt=Ke.attachmentPreviewsContainer;Te.classList.add("persona-relative"),Ce.classList.add("persona-relative");let kt=12,vt=()=>{var l;return(l=Se.label)!=null?l:""},Wt=()=>{var l;return(l=Se.iconName)!=null?l:"arrow-down"},Qt=()=>Se.enabled!==!1,Ft=()=>{var l;return(l=oe.mode)!=null?l:"anchor-top"},tn=()=>Ft()==="follow"||Ft()==="anchor-top"&&uo,Cr=()=>{var l;return(l=oe.anchorTopOffset)!=null?l:16},Fr=()=>{var l;return(l=oe.restorePosition)!=null?l:"bottom"},ar=()=>oe.pauseOnInteraction===!0,ir=()=>oe.showActivityWhilePinned!==!1,no=()=>oe.announce===!0,Vt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let lr=y("span","persona-flex persona-items-center"),_r=y("span",""),Bn=y("span","");Bn.setAttribute("data-persona-scroll-to-bottom-count",""),Bn.style.display="none",Vt.append(lr,_r,Bn),Te.appendChild(Vt);let Ln=y("div","persona-stream-anchor-spacer");Ln.setAttribute("aria-hidden","true"),Ln.setAttribute("data-persona-anchor-spacer",""),Ln.style.flexShrink="0",Ln.style.pointerEvents="none",Ln.style.height="0px",Ce.appendChild(Ln);let Dn=y("div","persona-sr-only");Dn.setAttribute("aria-live","polite"),Dn.setAttribute("aria-atomic","true"),Dn.setAttribute("role","status"),Dn.setAttribute("data-persona-live-region",""),Object.assign(Dn.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"}),Te.appendChild(Dn);let cr=null,Ar=null,ro=l=>{!no()||!l||(Ar=l,cr===null&&(cr=setTimeout(()=>{cr=null,Ar&&no()&&(Dn.textContent=Ar),Ar=null},400)))},Gn=()=>{let m=Be.style.display==="none"?0:Be.offsetHeight;Vt.style.bottom=`${m+kt}px`};Gn();let oo=()=>{let l=!!vt();Vt.setAttribute("aria-label",vt()||"Jump to latest"),Vt.title=vt(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),lr.innerHTML="";let m=he(Wt(),"14px","currentColor",2);m?(lr.appendChild(m),lr.style.display=""):lr.style.display="none",_r.textContent=vt(),_r.style.display=l?"":"none"};oo();let St=null,Sr=null,Tr=o.find(l=>l.renderHeader);if(Tr!=null&&Tr.renderHeader){let l=Tr.renderHeader({config:r,defaultRenderer:()=>{let m=Zr({config:r,showClose:O()});return cs(Te,m,r),m.header},onClose:()=>$t(!1,"user")});if(l){let m=Te.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),Le=l,nt.header.element=l)}}let $r=()=>{var m,h,x,S;if(!K)return;if(X=!0,!ke&&K&&(ke=Af({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>dr(),config:r,plugins:o,getThroughput:()=>{var H;return(H=Y==null?void 0:Y.getMetric())!=null?H:{status:"idle"}}})),ke&&(Ce.style.display="none",(m=Be.parentNode)==null||m.insertBefore(ke.element,Be),ke.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${kn.actionIconColor}`;let H=(S=(x=(h=r.features)==null?void 0:h.eventStream)==null?void 0:x.classNames)==null?void 0:S.toggleButtonActive;H&&H.split(/\s+/).forEach(q=>q&&bt.classList.add(q))}let l=()=>{if(!X)return;let H=Date.now();H-Re>=200&&(ke==null||ke.update(),Re=H),ce=requestAnimationFrame(l)};Re=0,ce=requestAnimationFrame(l),_n(),i.emit("eventStream:opened",{timestamp:Date.now()})},dr=()=>{var l,m,h;if(X){if(X=!1,ke&&ke.element.remove(),Ce.style.display="",bt){bt.style.boxShadow="";let x=(h=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;x&&x.split(/\s+/).forEach(S=>S&&bt.classList.remove(S))}ce!==null&&(cancelAnimationFrame(ce),ce=null),_n(),i.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(re){let l=(zd=(qd=r.features)==null?void 0:qd.eventStream)==null?void 0:zd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");bt=y("button",m),bt.style.width="28px",bt.style.height="28px",bt.style.color=kn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=he("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let x=Ke.clearChatButtonWrapper,S=Ke.closeButtonWrapper,H=x||S;H&&H.parentNode===Le?Le.insertBefore(bt,H):Le.appendChild(bt),bt.addEventListener("click",()=>{X?dr():$r()})}let Fo=l=>{var S,H,q,$,N;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let le=l.querySelector("[data-persona-composer-form]");le!=null&&le.parentNode?le.parentNode.insertBefore(h,le):l.insertBefore(h,l.firstChild)}if(!((H=l.querySelector("[data-persona-composer-attachment-input]"))!=null?H:l.querySelector('input[type="file"]'))){let le=y("input");le.type="file",le.setAttribute("data-persona-composer-attachment-input",""),le.accept=((q=m.allowedTypes)!=null?q:Yr).join(","),le.multiple=(($=m.maxFiles)!=null?$:4)>1,le.style.display="none",le.setAttribute("aria-label",(N=m.buttonTooltipText)!=null?N:"Attach files"),l.appendChild(le)}},Er=o.find(l=>l.renderComposer);if(Er!=null&&Er.renderComposer){let l=r.composer,m=Er.renderComposer({config:r,defaultRenderer:()=>qs({config:r}).footer,onSubmit:h=>{var q;if(!_||_.isStreaming())return;let x=h.trim(),S=(q=St==null?void 0:St.hasAttachments())!=null?q:!1;if(!x&&!S)return;zc();let H;S&&(H=[],H.push(...St.getContentParts()),x&&H.push(Ca(x))),_.sendMessage(x,{contentParts:H}),S&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Xe==null||Xe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Vd=r.voiceRecognition)==null?void 0:Vd.enabled)===!0?()=>{Sr==null||Sr()}:void 0});m&&(nt.replaceComposer(m),Be=nt.composer.footer)}let _o=l=>{let m=(...se)=>{for(let Z of se){let we=l.querySelector(Z);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),H=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(At=h),x&&(xe=x),S&&(ue=S),H&&(D=H,ve=H.parentElement),q&&(hn=q);let $=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(zt=$);let N=m("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(de=N,ht=N.parentElement),Xe=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Pt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(rt=le)};Fo(Be),_o(Be);let Pn=(Qd=(Kd=r.layout)==null?void 0:Kd.contentMaxWidth)!=null?Qd:W()?(Xd=(Jd=(Gd=r.launcher)==null?void 0:Gd.composerBar)==null?void 0:Jd.contentMaxWidth)!=null?Xd:"720px":void 0;if(Pn&&(et.style.maxWidth=Pn,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%"),Pn&&At&&!W()&&(At.style.maxWidth=Pn,At.style.marginLeft="auto",At.style.marginRight="auto"),Pn&&zt&&!W()&&(zt.style.maxWidth=Pn,zt.style.marginLeft="auto",zt.style.marginRight="auto"),Pn&&Pt&&!W()&&(Pt.style.maxWidth=Pn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),(Yd=r.attachments)!=null&&Yd.enabled&&Xe&&Pt){St=ls.fromConfig(r.attachments),St.setPreviewsContainer(Pt),Xe.addEventListener("change",h=>{let x=h.target;St==null||St.handleFileSelect(x.files),x.value=""});let l=r.attachments.dropOverlay,m=_f(l);Te.appendChild(m)}(()=>{var x,S;let l=(S=(x=r.layout)==null?void 0:x.slots)!=null?S:{},m=H=>{switch(H){case"body-top":return Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return et;case"footer-top":return zt;case"composer":return At;case"footer-bottom":return hn;default:return null}},h=(H,q)=>{var $;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")Le.insertBefore(q,Le.firstChild);else if(H==="header-right")Le.appendChild(q);else{let N=Le.querySelector(".persona-flex-col");N?($=N.parentNode)==null||$.insertBefore(q,N.nextSibling):Le.appendChild(q)}break;case"body-top":{let N=Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(q):Ce.insertBefore(q,Ce.firstChild);break}case"body-bottom":Ce.appendChild(q);break;case"footer-top":zt.replaceWith(q);break;case"footer-bottom":hn.replaceWith(q);break;default:break}};for(let[H,q]of Object.entries(l))if(q)try{let $=q({config:r,defaultContent:()=>m(H)});$&&h(H,$)}catch($){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,$)}})();let so=l=>{var q,$;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let H=h.getAttribute("data-bubble-type");if(H==="reasoning")Vs.has(S)?Vs.delete(S):Vs.add(S),cf(S,x);else if(H==="tool")Ks.has(S)?Ks.delete(S):Ks.add(S),df(S,x,r);else if(H==="approval"){let N=r.approval!==!1?r.approval:void 0,le=((q=N==null?void 0:N.detailsDisplay)!=null?q:"collapsed")==="expanded",se=($=ps.get(S))!=null?$:le;ps.set(S,!se),gf(S,x,r)}Pr.delete(S)};et.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),so(l))}),et.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),so(l))}),et.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let h=et.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let S=x.toString(),H=Og(S);!H||H===S||(m.setData("text/plain",H),l.preventDefault())});let jr=new Map,ao=null,io="idle",$o={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},jo=(l,m)=>{let{icon:h,label:x}=$o[m];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let S=he(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},lo=()=>{et.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var H;let h=m.closest("[data-actions-for]"),x=(H=h==null?void 0:h.getAttribute("data-actions-for"))!=null?H:null;jo(m,x&&x===ao?io:"idle")})};et.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let S=x.getAttribute("data-actions-for");if(!S)return;let H=h.getAttribute("data-action");if(H==="copy"){let N=_.getMessages().find(le=>le.id===S);if(N&&be.onCopy){let le=N.content||"";navigator.clipboard.writeText(le).then(()=>{h.classList.add("persona-message-action-success");let se=he("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=he("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),be.onCopy(N)}}else if(H==="read-aloud")_.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let N=((q=jr.get(S))!=null?q:null)===H,le=H==="upvote"?"thumbs-up":"thumbs-down";if(N){jr.delete(S),h.classList.remove("persona-message-action-active");let se=he(le,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=H==="upvote"?"downvote":"upvote",Z=x.querySelector(`[data-action="${se}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=he(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}jr.set(S,H),h.classList.add("persona-message-action-active");let we=he(le,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let _e=_.getMessages().find(Ue=>Ue.id===S);_e&&be.onFeedback&&be.onFeedback({type:H,messageId:_e.id,message:_e})}}}),et.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let H=h.getAttribute("data-approval-action");if(!H)return;let q=H==="approve"?"approved":"denied",N=_.getMessages().find(se=>se.id===S);if(!(N!=null&&N.approval))return;let le=x.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,q):_.resolveApproval(N.approval,q)});let wt=null,Nn=null,On={artifacts:[],selectedId:null},Cn=!1,Tt={current:null};et.addEventListener("click",l=>{var Z,we,Fe,_e,Ue;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||((Fe=(we=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:x}))===!0)return;let H=_.getArtifactById(x),q=H==null?void 0:H.markdown,$=(H==null?void 0:H.title)||"artifact";if(!q){let ze=h.closest("[data-open-artifact]"),mt=ze==null?void 0:ze.closest("[data-message-id]"),at=mt==null?void 0:mt.getAttribute("data-message-id");if(at){let We=_.getMessages().find(Ve=>Ve.id===at);if(We!=null&&We.rawContent)try{let Ve=JSON.parse(We.rawContent);q=(_e=Ve==null?void 0:Ve.props)==null?void 0:_e.markdown,$=((Ue=Ve==null?void 0:Ve.props)==null?void 0:Ue.title)||$}catch{}}}if(!q)return;let N=new Blob([q],{type:"text/markdown"}),le=URL.createObjectURL(N),se=document.createElement("a");se.href=le,se.download=`${$}.md`,se.click(),URL.revokeObjectURL(le)}),et.addEventListener("click",l=>{var H,q,$;let h=l.target.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||(($=(q=(H=r.features)==null?void 0:H.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:$.call(q,{type:"open",artifactId:x}))===!0||(l.preventDefault(),l.stopPropagation(),Cn=!1,_.selectArtifact(x),Mr())}),et.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Jn=Ke.composerOverlay,Xn=(l,m,h)=>{var $,N,le,se;let x=m.trim();if(!x||!Tt.current)return;let S=($=l.getAttribute("data-tool-call-id"))!=null?$:"",H=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:x,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?x.split(", "):[x],isFreeText:H,source:h.source},bubbles:!0,composed:!0})),Eo(Jn,S);let q=Tt.current.getMessages().find(Z=>{var we;return((we=Z.toolCall)==null?void 0:we.id)===S});(le=q==null?void 0:q.agentMetadata)!=null&&le.awaitingLocalTool?Tt.current.resolveAskUserQuestion(q,(se=h.structured)!=null?se:x):Tt.current.sendMessage(x)},Fn=l=>{var S;let m=Tt.current;if(!m)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",x=m.getMessages().find(H=>{var q;return((q=H.toolCall)==null?void 0:q.id)===h});x&&m.persistAskUserQuestionProgress(x,{answers:ti(l,x),currentIndex:rr(l)})},co=l=>Object.entries(l).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ae=l=>{var S,H,q;if(((H=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let m=rr(l),h=Ws(l);if(m>=h-1)return;let x=(q=Tt.current)==null?void 0:q.getMessages().find($=>{var N;return((N=$.toolCall)==null?void 0:N.id)===l.getAttribute("data-tool-call-id")});x&&(ni(l,x,r,m+1),Fn(l))};Jn.addEventListener("click",l=>{var H,q,$,N,le,se,Z,we,Fe,_e,Ue,ze,mt,at;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let S=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let De=(H=x.getAttribute("data-tool-call-id"))!=null?H:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:De},bubbles:!0,composed:!0})),Eo(Jn,De);let We=(q=Tt.current)==null?void 0:q.getMessages().find(Ve=>{var Qe;return((Qe=Ve.toolCall)==null?void 0:Qe.id)===De});($=We==null?void 0:We.agentMetadata)!=null&&$.awaitingLocalTool&&((N=Tt.current)==null||N.markAskUserQuestionResolved(We),(le=Tt.current)==null||le.resolveAskUserQuestion(We,"(dismissed)"));return}if(S==="pick"){let De=h.getAttribute("data-option-label");if(!De)return;let We=x.getAttribute("data-multi-select")==="true",Ve=To(x);if(Ve&&We){let Qe=os(x)[rr(x)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(De)?xt.delete(De):xt.add(De),Mo(x,Array.from(xt)),Fn(x);return}if(Ve){Mo(x,De),Fn(x),Ae(x);return}if(We){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let xt=x.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Pl(x).length===0);return}Xn(x,De,{source:"pick",values:[De]});return}if(S==="submit-multi"){let De=Pl(x);if(De.length===0)return;Xn(x,De.join(", "),{source:"multi",values:De});return}if(S==="open-free-text"){let De=x.querySelector('[data-ask-free-text-row="true"]');if(De){De.classList.remove("persona-hidden");let We=De.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(S==="focus-free-text"){let De=x.querySelector('[data-ask-free-text-input="true"]');De==null||De.focus();return}if(S==="submit-free-text"){let De=x.querySelector('[data-ask-free-text-input="true"]'),We=(se=De==null?void 0:De.value)!=null?se:"";if(!We.trim())return;if(To(x)){Mo(x,We.trim()),Fn(x),Ae(x);return}Xn(x,We,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Tt.current)return;let De=(Z=x.getAttribute("data-tool-call-id"))!=null?Z:"",We=Tt.current.getMessages().find(Ne=>{var He;return((He=Ne.toolCall)==null?void 0:He.id)===De});if(!We)return;let Ve=x.querySelector('[data-ask-free-text-input="true"]'),Qe=(Fe=(we=Ve==null?void 0:Ve.value)==null?void 0:we.trim())!=null?Fe:"";if(Qe){let Ne=os(x)[rr(x)];(typeof Ne!="string"||Ne!==Qe)&&Mo(x,Qe)}let xt=S==="next"?1:-1,B=rr(x)+xt;ni(x,We,r,B),Fn(x);return}if(S==="submit-all"){if(!Tt.current)return;let De=(_e=x.getAttribute("data-tool-call-id"))!=null?_e:"",We=Tt.current.getMessages().find(Ne=>{var He;return((He=Ne.toolCall)==null?void 0:He.id)===De});if(!We)return;let Ve=x.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(Ue=Ve==null?void 0:Ve.value)==null?void 0:Ue.trim())!=null?ze:"";Qe&&Mo(x,Qe);let xt=ti(x,We);Tt.current.persistAskUserQuestionProgress(We,{answers:xt,currentIndex:rr(x)});let B=co(xt);Xn(x,B||"(submitted)",{source:"submit-all",structured:xt});return}if(S==="skip"){if(!Tt.current)return;let De=(mt=x.getAttribute("data-tool-call-id"))!=null?mt:"",We=Tt.current.getMessages().find(He=>{var Ze;return((Ze=He.toolCall)==null?void 0:Ze.id)===De});if(!We)return;let Ve=To(x),Qe=rr(x),xt=Ws(x),B=Qe>=xt-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:De},bubbles:!0,composed:!0})),Eo(Jn,De),(at=We.agentMetadata)!=null&&at.awaitingLocalTool&&(Tt.current.markAskUserQuestionResolved(We),Tt.current.resolveAskUserQuestion(We,"(dismissed)"));return}Mo(x,"");let Ne=x.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),B){let He=ti(x,We),Ze=co(He);Xn(x,Ze||"(skipped)",{source:"submit-all",structured:He});return}ni(x,We,r,Qe+1),Fn(x);return}}),Jn.addEventListener("keydown",l=>{var H;if(l.key!=="Enter")return;let h=l.target;if(!((H=h.matches)!=null&&H.call(h,'[data-ask-free-text-input="true"]')))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let S=h.value;if(S.trim()){if(To(x)){Mo(x,S.trim()),Fn(x),Ae(x);return}Xn(x,S,{source:"free-text"})}});let Ur=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Jn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),H=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];H&&(l.preventDefault(),H.click())};document.addEventListener("keydown",Ur);let Qn=null,_t=null,Yn=null,qr=null,Qs=()=>{};function hs(){qr==null||qr(),qr=null}let Ys=()=>{var q;if(!Qn||!_t)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){_t.style.removeProperty("position"),_t.style.removeProperty("left"),_t.style.removeProperty("top"),_t.style.removeProperty("bottom"),_t.style.removeProperty("width"),_t.style.removeProperty("z-index");return}let x=Qn.firstElementChild;if(!x||x===_t)return;let S=10;_t.style.position="absolute",_t.style.top="0",_t.style.bottom="0",_t.style.width=`${S}px`,_t.style.zIndex="5";let H=x.offsetWidth-S/2;_t.style.left=`${Math.max(0,H)}px`},Uo=()=>{},Mr=()=>{var h,x,S,H,q;if(!wt||!sr(r))return;Ki(e,r),Gi(e,r),Uo();let l=(H=(S=(x=(h=r.features)==null?void 0:h.artifacts)==null?void 0:x.layout)==null?void 0:S.narrowHostMaxWidth)!=null?H:520,m=Q.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),wt.update(On),Cn?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(q=wt.backdrop)==null||q.classList.add("persona-hidden")):On.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),Qs()};if(sr(r)){Q.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Te),wt=Ef(r,{onSelect:h=>{var x;return(x=Tt.current)==null?void 0:x.selectArtifact(h)},onDismiss:()=>{Cn=!0,Mr()}}),wt.element.classList.add("persona-hidden"),Qn=m,m.appendChild(l),m.appendChild(wt.element),wt.backdrop&&Q.appendChild(wt.backdrop),Q.appendChild(m),Qs=()=>{var x,S,H,q;if(!Qn||!wt)return;if(!(((H=(S=(x=r.features)==null?void 0:x.artifacts)==null?void 0:S.layout)==null?void 0:H.resizable)===!0)){Yn==null||Yn(),Yn=null,hs(),_t&&(_t.remove(),_t=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!_t){let $=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");$.setAttribute("role","separator"),$.setAttribute("aria-orientation","vertical"),$.setAttribute("aria-label","Resize artifacts panel"),$.tabIndex=0;let N=e.ownerDocument,le=(q=N.defaultView)!=null?q:window,se=Z=>{var mt,at;if(!wt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||le.innerWidth<=640)return;Z.preventDefault(),hs();let we=Z.clientX,Fe=wt.element.getBoundingClientRect().width,_e=(at=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:at.layout,Ue=De=>{let We=Qn.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),Qe=Ve?0:Pf(Qn,le),xt=Ve?0:$.getBoundingClientRect().width||6,B=Fe-(De.clientX-we),Ne=If(B,We,Qe,xt,_e==null?void 0:_e.resizableMinWidth,_e==null?void 0:_e.resizableMaxWidth);wt.element.style.width=`${Ne}px`,wt.element.style.maxWidth="none",Ys()},ze=()=>{N.removeEventListener("pointermove",Ue),N.removeEventListener("pointerup",ze),N.removeEventListener("pointercancel",ze),qr=null;try{$.releasePointerCapture(Z.pointerId)}catch{}};qr=ze,N.addEventListener("pointermove",Ue),N.addEventListener("pointerup",ze),N.addEventListener("pointercancel",ze);try{$.setPointerCapture(Z.pointerId)}catch{}};$.addEventListener("pointerdown",se),_t=$,Qn.insertBefore($,wt.element),Yn=()=>{$.removeEventListener("pointerdown",se)}}if(_t){let $=On.artifacts.length>0&&!Cn;_t.classList.toggle("persona-hidden",!$),Ys()}},Uo=()=>{var le,se,Z,we,Fe,_e,Ue,ze,mt,at,De,We,Ve,Qe;if(!I||!wt||((se=(le=r.launcher)==null?void 0:le.sidebarMode)!=null?se:!1)||on(r)&&Vn(r).reveal==="emerge")return;let x=(Z=e.ownerDocument.defaultView)!=null?Z:window,S=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,H=(Ue=(_e=r.launcher)==null?void 0:_e.mobileBreakpoint)!=null?Ue:640;if(S&&x.innerWidth<=H||!Lf(r,I))return;let q=(at=(mt=(ze=r.launcher)==null?void 0:ze.width)!=null?mt:r.launcherWidth)!=null?at:zn,$=(Qe=(Ve=(We=(De=r.features)==null?void 0:De.artifacts)==null?void 0:We.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Cn?(Q.style.width=$,Q.style.maxWidth=$):(Q.style.width=q,Q.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{Mr()}),Nn.observe(Q))}else Q.appendChild(Te),W()&&lt&&(Ke.peekBanner&&lt.appendChild(Ke.peekBanner),lt.appendChild(Be));e.appendChild(fe),lt&&e.appendChild(lt);let po=()=>{var Ne,He,Ze,It,$e,Jt,Ct,cn,Wn,Dt,gn,$n,Je,Rt,jn,Go,Jo,Xo,Qo,Ts,Es,Xt,Yo,vo,wo,Gr,Zo,tt;if(W()){Q.style.width="100%",Q.style.maxWidth="100%";let Ot=(He=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?He:{},Nt=fe.dataset.state==="expanded",Kt=(Ze=Ot.expandedSize)!=null?Ze:"anchored";if(!(Nt&&Kt!=="fullscreen")){Te.style.background="",Te.style.border="",Te.style.borderRadius="",Te.style.overflow="",Te.style.boxShadow="";return}let gt=($e=(It=r.theme)==null?void 0:It.components)==null?void 0:$e.panel,Ut=$s(r),fn=(mn,nr)=>{var Co;return mn==null||mn===""?nr:(Co=Fs(Ut,mn))!=null?Co:mn},Un="1px solid var(--persona-border)",Hr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",un="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Te.style.background="var(--persona-surface, #ffffff)",Te.style.border=fn(gt==null?void 0:gt.border,Un),Te.style.borderRadius=fn(gt==null?void 0:gt.borderRadius,un),Te.style.boxShadow=fn(gt==null?void 0:gt.shadow,Hr),Te.style.overflow="hidden";return}let l=on(r),m=(Ct=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?Ct:!1,h=l||m||((Wn=(cn=r.launcher)==null?void 0:cn.fullHeight)!=null?Wn:!1),x=((Dt=r.launcher)==null?void 0:Dt.enabled)===!1,S=($n=(gn=r.theme)==null?void 0:gn.components)==null?void 0:$n.panel,H=$s(r),q=(Ot,Nt)=>{var Kt;return Ot==null||Ot===""?Nt:(Kt=Fs(H,Ot))!=null?Kt:Ot},$=(Je=e.ownerDocument.defaultView)!=null?Je:window,N=(jn=(Rt=r.launcher)==null?void 0:Rt.mobileFullscreen)!=null?jn:!0,le=(Jo=(Go=r.launcher)==null?void 0:Go.mobileBreakpoint)!=null?Jo:640,se=$.innerWidth<=le,Z=N&&se&&I,we=(Qo=(Xo=r.launcher)==null?void 0:Xo.position)!=null?Qo:"bottom-left",Fe=we==="bottom-left"||we==="top-left",_e=(Es=(Ts=r.launcher)==null?void 0:Ts.zIndex)!=null?Es:vn,Ue=m||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":m?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",Ue="none");let mt=m||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=q(S==null?void 0:S.border,Ue),De=q(S==null?void 0:S.shadow,ze),We=q(S==null?void 0:S.borderRadius,mt),Ve=Ce.scrollTop;e.style.cssText="",fe.style.cssText="",Q.style.cssText="",Te.style.cssText="",Ce.style.cssText="",Be.style.cssText="",X&&(Ce.style.display="none");let Qe=()=>{var Nt;if(Ve<=0)return;((Nt=Ce.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(Ce.scrollTop===Ve)return;let Kt=Ce.scrollHeight-Ce.clientHeight;Kt<=0||(Ce.scrollTop=Math.min(Ve,Kt))})};if(Z){fe.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"),fe.style.cssText=`
34
+ `,B.addEventListener("click",()=>{u=T,E.forEach((q,U)=>{let L=U<T;q.classList.toggle("selected",L),q.setAttribute("aria-checked",U===T-1?"true":"false")})}),E.push(B),S.appendChild(B)}f.appendChild(S);let P=null;if(d){let T=document.createElement("div");T.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),T.appendChild(P),f.appendChild(T)}let H=document.createElement("div");H.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{n==null||n(),p.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let T=(P==null?void 0:P.value.trim())||void 0;await t(u,T),p.remove()}catch(T){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",T)}}),H.appendChild(W),H.appendChild(I),f.appendChild(H),p.appendChild(f),p}function sl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,y.appendChild(v);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,y.appendChild(S),g.appendChild(y);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=p,P.appendChild(H),P.appendChild(W);let I=document.createElement("div");I.className="persona-feedback-numbers";let T=[];for(let F=0;F<=10;F++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${F} out of 10`),_.textContent=String(F),_.dataset.rating=String(F),F<=6?_.classList.add("persona-feedback-detractor"):F<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{f=F,T.forEach((ee,Me)=>{ee.classList.toggle("selected",Me===F),ee.setAttribute("aria-checked",Me===F?"true":"false")})}),T.push(_),I.appendChild(_)}E.appendChild(P),E.appendChild(I),g.appendChild(E);let B=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),F.appendChild(B),g.appendChild(F)}let q=document.createElement("div");q.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=i,U.addEventListener("click",()=>{n==null||n(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let F=(B==null?void 0:B.value.trim())||void 0;await t(f,F),u.remove()}catch(F){L.disabled=!1,L.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),q.appendChild(U),q.appendChild(L),g.appendChild(q),u.appendChild(g),u}var ea="persona-chat-history",Zx=30*1e3,ev={"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 tv(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=ev[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function al(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 nv(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function rv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Sc=e=>!e||typeof e!="object"?{}:{...e},Xf=e=>e.map(t=>({...t,streaming:!1})),Qf=(e,t,n)=>{let r=e!=null&&e.markdown?ss(e.markdown):null,o=Ws(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=os()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});c=o?o(g):g}else if(r){let g=s.streaming?Jm(a):a,y=r(g);c=o&&d?o(y):y}else c=Br(a);return c}};function Yf(e){var i,d,c,p;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=he(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=b("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var il=(e,t,n)=>{var kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Ei(t),o=ja.getForInstance(r.plugins),{plugin:s,teardown:a}=Pf();r.components&&ro.registerAll(r.components);let i=zf(),c=r.persistState===!1?null:(kd=r.storageAdapter)!=null?kd:el(),p={},u=null,f=!1,g=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:x}=m;return x&&(f=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")u=l.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=l!=null?l:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=Sc(h.metadata)),(Ld=h.messages)!=null&&Ld.length&&(r={...r,initialMessages:h.messages}),(Pd=h.artifacts)!=null&&Pd.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Id=h.selectedArtifactId)!=null?Id:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=g({messages:[],metadata:{}});(Rd=l.messages)!=null&&Rd.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>p,v=l=>{var h;p=(h=l({...p}))!=null?h:{},Rr()},S=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ua],E=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[hs.message,hs.messageAndClick],P=qa({parsers:S,handlers:E,getSessionMetadata:y,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});P.syncFromMetadata();let H=(Hd=(Wd=r.launcher)==null?void 0:Wd.enabled)!=null?Hd:!0,W=(Dd=(Bd=r.launcher)==null?void 0:Bd.autoExpand)!=null?Dd:!1,I=(Nd=r.autoFocusInput)!=null?Nd:!1,T=W,B=H,q=(Fd=(Od=r.layout)==null?void 0:Od.header)==null?void 0:Fd.layout,U=!1,L=()=>Oo(r),F=()=>H||L(),_=L()?!1:H?W:!0,ee=!1,Me=null,pe=()=>{ee=!0,Me&&clearTimeout(Me),Me=setTimeout(()=>{ee&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ee=!1)},1e4)},te=Qf(r,P,pe),Pe=($d=(_d=r.features)==null?void 0:_d.showReasoning)!=null?$d:!0,Ie=(Ud=(jd=r.features)==null?void 0:jd.showToolCalls)!=null?Ud:!0,re=(zd=(qd=r.features)==null?void 0:qd.showEventStreamToggle)!=null?zd:!1,Se=(Kd=(Vd=r.features)==null?void 0:Vd.scrollToBottom)!=null?Kd:{},oe=(Jd=(Gd=r.features)==null?void 0:Gd.scrollBehavior)!=null?Jd:{},ie=`${(Qd=typeof r.persistState=="object"?(Xd=r.persistState)==null?void 0:Xd.keyPrefix:void 0)!=null?Qd:"persona-"}event-stream`,ye=re?new _a(ie):null,je=(ep=(Zd=(Yd=r.features)==null?void 0:Yd.eventStream)==null?void 0:Zd.maxEvents)!=null?ep:2e3,K=re?new Fa(je,ye):null,Y=re?new $a:null,ke=null,X=!1,ce=null,Re=0;ye==null||ye.open().then(()=>K==null?void 0:K.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let be={onCopy:l=>{var m,h;i.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,l)},onFeedback:l=>{var m,h;i.emit("message:feedback",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,l)}},Ge=(tp=r.statusIndicator)!=null?tp:{},ft=l=>{var m,h,x,C,k,j;return l==="idle"?(m=Ge.idleText)!=null?m:nn.idle:l==="connecting"?(h=Ge.connectingText)!=null?h:nn.connecting:l==="connected"?(x=Ge.connectedText)!=null?x:nn.connected:l==="error"?(C=Ge.errorText)!=null?C:nn.error:l==="paused"?(k=Ge.pausedText)!=null?k:nn.paused:l==="resuming"?(j=Ge.resumingText)!=null?j:nn.resuming:nn[l]};function Ht(l,m,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let C=document.createElement("a");C.href=h.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=m,C.style.color="inherit",C.style.textDecoration="none",l.appendChild(C)}else l.textContent=m}let nt=yf({config:r,showClose:F()}),{wrapper:fe,panel:Q,pillRoot:lt}=nt.shell,Ke=nt.panelElements,{container:Te,body:Ce,messagesWrapper:et,suggestions:zt,textarea:xe,sendButton:ue,sendButtonWrapper:An,composerForm:At,statusText:bn,introTitle:xr,introSubtitle:vr,closeButton:qe,iconHolder:M,headerTitle:me,headerSubtitle:Ee,header:Le,footer:Be,actionsRow:rt,leftActions:Ye,rightActions:yt}=Ke,ge=Ke.setSendButtonMode,D=Ke.micButton,ve=Ke.micButtonWrapper,de=Ke.attachmentButton,ht=Ke.attachmentButtonWrapper,Xe=Ke.attachmentInput,Pt=Ke.attachmentPreviewsContainer;Te.classList.add("persona-relative"),Ce.classList.add("persona-relative");let kt=12,vt=()=>{var l;return(l=Se.label)!=null?l:""},Wt=()=>{var l;return(l=Se.iconName)!=null?l:"arrow-down"},Qt=()=>Se.enabled!==!1,Ft=()=>{var l;return(l=oe.mode)!=null?l:"anchor-top"},en=()=>Ft()==="follow"||Ft()==="anchor-top"&&fo,wr=()=>{var l;return(l=oe.anchorTopOffset)!=null?l:16},Fr=()=>{var l;return(l=oe.restorePosition)!=null?l:"bottom"},ar=()=>oe.pauseOnInteraction===!0,ir=()=>oe.showActivityWhilePinned!==!1,so=()=>oe.announce===!0,Vt=b("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");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let lr=b("span","persona-flex persona-items-center"),_r=b("span",""),Bn=b("span","");Bn.setAttribute("data-persona-scroll-to-bottom-count",""),Bn.style.display="none",Vt.append(lr,_r,Bn),Te.appendChild(Vt);let In=b("div","persona-stream-anchor-spacer");In.setAttribute("aria-hidden","true"),In.setAttribute("data-persona-anchor-spacer",""),In.style.flexShrink="0",In.style.pointerEvents="none",In.style.height="0px",Ce.appendChild(In);let Dn=b("div","persona-sr-only");Dn.setAttribute("aria-live","polite"),Dn.setAttribute("aria-atomic","true"),Dn.setAttribute("role","status"),Dn.setAttribute("data-persona-live-region",""),Object.assign(Dn.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"}),Te.appendChild(Dn);let cr=null,Cr=null,ao=l=>{!so()||!l||(Cr=l,cr===null&&(cr=setTimeout(()=>{cr=null,Cr&&so()&&(Dn.textContent=Cr),Cr=null},400)))},Gn=()=>{let m=Be.style.display==="none"?0:Be.offsetHeight;Vt.style.bottom=`${m+kt}px`};Gn();let io=()=>{let l=!!vt();Vt.setAttribute("aria-label",vt()||"Jump to latest"),Vt.title=vt(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),lr.innerHTML="";let m=he(Wt(),"14px","currentColor",2);m?(lr.appendChild(m),lr.style.display=""):lr.style.display="none",_r.textContent=vt(),_r.style.display=l?"":"none"};io();let St=null,Ar=null,Sr=o.find(l=>l.renderHeader);if(Sr!=null&&Sr.renderHeader){let l=Sr.renderHeader({config:r,defaultRenderer:()=>{let m=no({config:r,showClose:F()});return ps(Te,m,r),m.header},onClose:()=>$t(!1,"user")});if(l){let m=Te.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),Le=l,nt.header.element=l)}}let $r=()=>{var m,h,x,C;if(!K)return;if(X=!0,!ke&&K&&(ke=Bf({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>dr(),config:r,plugins:o,getThroughput:()=>{var k;return(k=Y==null?void 0:Y.getMetric())!=null?k:{status:"idle"}}})),ke&&(Ce.style.display="none",(m=Be.parentNode)==null||m.insertBefore(ke.element,Be),ke.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let k=(C=(x=(h=r.features)==null?void 0:h.eventStream)==null?void 0:x.classNames)==null?void 0:C.toggleButtonActive;k&&k.split(/\s+/).forEach(j=>j&&bt.classList.add(j))}let l=()=>{if(!X)return;let k=Date.now();k-Re>=200&&(ke==null||ke.update(),Re=k),ce=requestAnimationFrame(l)};Re=0,ce=requestAnimationFrame(l),_n(),i.emit("eventStream:opened",{timestamp:Date.now()})},dr=()=>{var l,m,h;if(X){if(X=!1,ke&&ke.element.remove(),Ce.style.display="",bt){bt.style.boxShadow="";let x=(h=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;x&&x.split(/\s+/).forEach(C=>C&&bt.classList.remove(C))}ce!==null&&(cancelAnimationFrame(ce),ce=null),_n(),i.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(re){let l=(rp=(np=r.features)==null?void 0:np.eventStream)==null?void 0:rp.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");bt=b("button",m),bt.style.width="28px",bt.style.height="28px",bt.style.color=Pn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=he("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let x=Ke.clearChatButtonWrapper,C=Ke.closeButtonWrapper,k=x||C;k&&k.parentNode===Le?Le.insertBefore(bt,k):Le.appendChild(bt),bt.addEventListener("click",()=>{X?dr():$r()})}let $o=l=>{var C,k,j,O,N;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(C=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?C:l.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let le=l.querySelector("[data-persona-composer-form]");le!=null&&le.parentNode?le.parentNode.insertBefore(h,le):l.insertBefore(h,l.firstChild)}if(!((k=l.querySelector("[data-persona-composer-attachment-input]"))!=null?k:l.querySelector('input[type="file"]'))){let le=b("input");le.type="file",le.setAttribute("data-persona-composer-attachment-input",""),le.accept=((j=m.allowedTypes)!=null?j:to).join(","),le.multiple=((O=m.maxFiles)!=null?O:4)>1,le.style.display="none",le.setAttribute("aria-label",(N=m.buttonTooltipText)!=null?N:"Attach files"),l.appendChild(le)}},Tr=o.find(l=>l.renderComposer);if(Tr!=null&&Tr.renderComposer){let l=r.composer,m=Tr.renderComposer({config:r,defaultRenderer:()=>Gs({config:r}).footer,onSubmit:h=>{var j;if(!$||$.isStreaming())return;let x=h.trim(),C=(j=St==null?void 0:St.hasAttachments())!=null?j:!1;if(!x&&!C)return;rd();let k;C&&(k=[],k.push(...St.getContentParts()),x&&k.push(Ta(x))),$.sendMessage(x,{contentParts:k}),C&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Xe==null||Xe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((op=r.voiceRecognition)==null?void 0:op.enabled)===!0?()=>{Ar==null||Ar()}:void 0});m&&(nt.replaceComposer(m),Be=nt.composer.footer)}let jo=l=>{let m=(...se)=>{for(let Z of se){let we=l.querySelector(Z);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),C=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),j=l.querySelector("[data-persona-composer-status]");h&&(At=h),x&&(xe=x),C&&(ue=C),k&&(D=k,ve=k.parentElement),j&&(bn=j);let O=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(zt=O);let N=m("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(de=N,ht=N.parentElement),Xe=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Pt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(rt=le)};$o(Be),jo(Be);let Rn=(cp=(sp=r.layout)==null?void 0:sp.contentMaxWidth)!=null?cp:L()?(lp=(ip=(ap=r.launcher)==null?void 0:ap.composerBar)==null?void 0:ip.contentMaxWidth)!=null?lp:"720px":void 0;if(Rn&&(et.style.maxWidth=Rn,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%"),Rn&&At&&!L()&&(At.style.maxWidth=Rn,At.style.marginLeft="auto",At.style.marginRight="auto"),Rn&&zt&&!L()&&(zt.style.maxWidth=Rn,zt.style.marginLeft="auto",zt.style.marginRight="auto"),Rn&&Pt&&!L()&&(Pt.style.maxWidth=Rn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),(dp=r.attachments)!=null&&dp.enabled&&Xe&&Pt){St=ds.fromConfig(r.attachments),St.setPreviewsContainer(Pt),Xe.addEventListener("change",h=>{let x=h.target;St==null||St.handleFileSelect(x.files),x.value=""});let l=r.attachments.dropOverlay,m=Yf(l);Te.appendChild(m)}(()=>{var x,C;let l=(C=(x=r.layout)==null?void 0:x.slots)!=null?C:{},m=k=>{switch(k){case"body-top":return Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return et;case"footer-top":return zt;case"composer":return At;case"footer-bottom":return bn;default:return null}},h=(k,j)=>{var O;switch(k){case"header-left":case"header-center":case"header-right":if(k==="header-left")Le.insertBefore(j,Le.firstChild);else if(k==="header-right")Le.appendChild(j);else{let N=Le.querySelector(".persona-flex-col");N?(O=N.parentNode)==null||O.insertBefore(j,N.nextSibling):Le.appendChild(j)}break;case"body-top":{let N=Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(j):Ce.insertBefore(j,Ce.firstChild);break}case"body-bottom":Ce.appendChild(j);break;case"footer-top":zt.replaceWith(j);break;case"footer-bottom":bn.replaceWith(j);break;default:break}};for(let[k,j]of Object.entries(l))if(j)try{let O=j({config:r,defaultContent:()=>m(k)});O&&h(k,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${k}":`,O)}})();let lo=l=>{var j,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let C=x.getAttribute("data-message-id");if(!C)return;let k=h.getAttribute("data-bubble-type");if(k==="reasoning")Xs.has(C)?Xs.delete(C):Xs.add(C),wf(C,x);else if(k==="tool")Qs.has(C)?Qs.delete(C):Qs.add(C),Cf(C,x,r);else if(k==="approval"){let N=r.approval!==!1?r.approval:void 0,le=((j=N==null?void 0:N.detailsDisplay)!=null?j:"collapsed")==="expanded",se=(O=ms.get(C))!=null?O:le;ms.set(C,!se),Ef(C,x,r)}Lr.delete(C)};et.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lo(l))}),et.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lo(l))}),et.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let h=et.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let C=x.toString(),k=Xg(C);!k||k===C||(m.setData("text/plain",k),l.preventDefault())});let jr=new Map,co=null,po="idle",Uo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},qo=(l,m)=>{let{icon:h,label:x}=Uo[m];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let C=he(h,14,"currentColor",2);C&&(l.innerHTML="",l.appendChild(C))},uo=()=>{et.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var k;let h=m.closest("[data-actions-for]"),x=(k=h==null?void 0:h.getAttribute("data-actions-for"))!=null?k:null;qo(m,x&&x===co?po:"idle")})};et.addEventListener("click",l=>{var j;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let C=x.getAttribute("data-actions-for");if(!C)return;let k=h.getAttribute("data-action");if(k==="copy"){let N=$.getMessages().find(le=>le.id===C);if(N&&be.onCopy){let le=N.content||"";navigator.clipboard.writeText(le).then(()=>{h.classList.add("persona-message-action-success");let se=he("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=he("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),be.onCopy(N)}}else if(k==="read-aloud")$.toggleReadAloud(C);else if(k==="upvote"||k==="downvote"){let N=((j=jr.get(C))!=null?j:null)===k,le=k==="upvote"?"thumbs-up":"thumbs-down";if(N){jr.delete(C),h.classList.remove("persona-message-action-active");let se=he(le,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=k==="upvote"?"downvote":"upvote",Z=x.querySelector(`[data-action="${se}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=he(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}jr.set(C,k),h.classList.add("persona-message-action-active");let we=he(le,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let _e=$.getMessages().find(Ue=>Ue.id===C);_e&&be.onFeedback&&be.onFeedback({type:k,messageId:_e.id,message:_e})}}}),et.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let C=x.getAttribute("data-message-id");if(!C)return;let k=h.getAttribute("data-approval-action");if(!k)return;let j=k==="approve"?"approved":"denied",N=$.getMessages().find(se=>se.id===C);if(!(N!=null&&N.approval))return;let le=x.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?$.resolveWebMcpApproval(C,j):$.resolveApproval(N.approval,j)});let wt=null,Nn=null,On={artifacts:[],selectedId:null},Sn=!1,Tt={current:null};et.addEventListener("click",l=>{var Z,we,Fe,_e,Ue;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||((Fe=(we=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:x}))===!0)return;let k=$.getArtifactById(x),j=k==null?void 0:k.markdown,O=(k==null?void 0:k.title)||"artifact";if(!j){let ze=h.closest("[data-open-artifact]"),mt=ze==null?void 0:ze.closest("[data-message-id]"),at=mt==null?void 0:mt.getAttribute("data-message-id");if(at){let We=$.getMessages().find(Ve=>Ve.id===at);if(We!=null&&We.rawContent)try{let Ve=JSON.parse(We.rawContent);j=(_e=Ve==null?void 0:Ve.props)==null?void 0:_e.markdown,O=((Ue=Ve==null?void 0:Ve.props)==null?void 0:Ue.title)||O}catch{}}}if(!j)return;let N=new Blob([j],{type:"text/markdown"}),le=URL.createObjectURL(N),se=document.createElement("a");se.href=le,se.download=`${O}.md`,se.click(),URL.revokeObjectURL(le)}),et.addEventListener("click",l=>{var k,j,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||((O=(j=(k=r.features)==null?void 0:k.artifacts)==null?void 0:j.onArtifactAction)==null?void 0:O.call(j,{type:"open",artifactId:x}))===!0||(l.preventDefault(),l.stopPropagation(),Sn=!1,$.selectArtifact(x),Er())}),et.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Jn=Ke.composerOverlay,Xn=(l,m,h)=>{var O,N,le,se;let x=m.trim();if(!x||!Tt.current)return;let C=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",k=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:x,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?x.split(", "):[x],isFreeText:k,source:h.source},bubbles:!0,composed:!0})),ko(Jn,C);let j=Tt.current.getMessages().find(Z=>{var we;return((we=Z.toolCall)==null?void 0:we.id)===C});(le=j==null?void 0:j.agentMetadata)!=null&&le.awaitingLocalTool?Tt.current.resolveAskUserQuestion(j,(se=h.structured)!=null?se:x):Tt.current.sendMessage(x)},Fn=l=>{var C;let m=Tt.current;if(!m)return;let h=(C=l.getAttribute("data-tool-call-id"))!=null?C:"",x=m.getMessages().find(k=>{var j;return((j=k.toolCall)==null?void 0:j.id)===h});x&&m.persistAskUserQuestionProgress(x,{answers:ai(l,x),currentIndex:rr(l)})},mo=l=>Object.entries(l).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ae=l=>{var C,k,j;if(((k=(C=r.features)==null?void 0:C.askUserQuestion)==null?void 0:k.groupedAutoAdvance)===!1)return;let m=rr(l),h=Ds(l);if(m>=h-1)return;let x=(j=Tt.current)==null?void 0:j.getMessages().find(O=>{var N;return((N=O.toolCall)==null?void 0:N.id)===l.getAttribute("data-tool-call-id")});x&&(ii(l,x,r,m+1),Fn(l))};Jn.addEventListener("click",l=>{var k,j,O,N,le,se,Z,we,Fe,_e,Ue,ze,mt,at;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let C=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),C==="dismiss"){let De=(k=x.getAttribute("data-tool-call-id"))!=null?k:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:De},bubbles:!0,composed:!0})),ko(Jn,De);let We=(j=Tt.current)==null?void 0:j.getMessages().find(Ve=>{var Qe;return((Qe=Ve.toolCall)==null?void 0:Qe.id)===De});(O=We==null?void 0:We.agentMetadata)!=null&&O.awaitingLocalTool&&((N=Tt.current)==null||N.markAskUserQuestionResolved(We),(le=Tt.current)==null||le.resolveAskUserQuestion(We,"(dismissed)"));return}if(C==="pick"){let De=h.getAttribute("data-option-label");if(!De)return;let We=x.getAttribute("data-multi-select")==="true",Ve=Mo(x);if(Ve&&We){let Qe=as(x)[rr(x)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(De)?xt.delete(De):xt.add(De),Lo(x,Array.from(xt)),Fn(x);return}if(Ve){Lo(x,De),Fn(x),Ae(x);return}if(We){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let xt=x.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Ol(x).length===0);return}Xn(x,De,{source:"pick",values:[De]});return}if(C==="submit-multi"){let De=Ol(x);if(De.length===0)return;Xn(x,De.join(", "),{source:"multi",values:De});return}if(C==="open-free-text"){let De=x.querySelector('[data-ask-free-text-row="true"]');if(De){De.classList.remove("persona-hidden");let We=De.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(C==="focus-free-text"){let De=x.querySelector('[data-ask-free-text-input="true"]');De==null||De.focus();return}if(C==="submit-free-text"){let De=x.querySelector('[data-ask-free-text-input="true"]'),We=(se=De==null?void 0:De.value)!=null?se:"";if(!We.trim())return;if(Mo(x)){Lo(x,We.trim()),Fn(x),Ae(x);return}Xn(x,We,{source:"free-text"});return}if(C==="next"||C==="back"){if(!Tt.current)return;let De=(Z=x.getAttribute("data-tool-call-id"))!=null?Z:"",We=Tt.current.getMessages().find(Ne=>{var He;return((He=Ne.toolCall)==null?void 0:He.id)===De});if(!We)return;let Ve=x.querySelector('[data-ask-free-text-input="true"]'),Qe=(Fe=(we=Ve==null?void 0:Ve.value)==null?void 0:we.trim())!=null?Fe:"";if(Qe){let Ne=as(x)[rr(x)];(typeof Ne!="string"||Ne!==Qe)&&Lo(x,Qe)}let xt=C==="next"?1:-1,R=rr(x)+xt;ii(x,We,r,R),Fn(x);return}if(C==="submit-all"){if(!Tt.current)return;let De=(_e=x.getAttribute("data-tool-call-id"))!=null?_e:"",We=Tt.current.getMessages().find(Ne=>{var He;return((He=Ne.toolCall)==null?void 0:He.id)===De});if(!We)return;let Ve=x.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(Ue=Ve==null?void 0:Ve.value)==null?void 0:Ue.trim())!=null?ze:"";Qe&&Lo(x,Qe);let xt=ai(x,We);Tt.current.persistAskUserQuestionProgress(We,{answers:xt,currentIndex:rr(x)});let R=mo(xt);Xn(x,R||"(submitted)",{source:"submit-all",structured:xt});return}if(C==="skip"){if(!Tt.current)return;let De=(mt=x.getAttribute("data-tool-call-id"))!=null?mt:"",We=Tt.current.getMessages().find(He=>{var Ze;return((Ze=He.toolCall)==null?void 0:Ze.id)===De});if(!We)return;let Ve=Mo(x),Qe=rr(x),xt=Ds(x),R=Qe>=xt-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:De},bubbles:!0,composed:!0})),ko(Jn,De),(at=We.agentMetadata)!=null&&at.awaitingLocalTool&&(Tt.current.markAskUserQuestionResolved(We),Tt.current.resolveAskUserQuestion(We,"(dismissed)"));return}Lo(x,"");let Ne=x.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),R){let He=ai(x,We),Ze=mo(He);Xn(x,Ze||"(skipped)",{source:"submit-all",structured:He});return}ii(x,We,r,Qe+1),Fn(x);return}}),Jn.addEventListener("keydown",l=>{var k;if(l.key!=="Enter")return;let h=l.target;if(!((k=h.matches)!=null&&k.call(h,'[data-ask-free-text-input="true"]')))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let C=h.value;if(C.trim()){if(Mo(x)){Lo(x,C.trim()),Fn(x),Ae(x);return}Xn(x,C,{source:"free-text"})}});let Ur=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Jn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),k=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];k&&(l.preventDefault(),k.click())};document.addEventListener("keydown",Ur);let Qn=null,_t=null,Yn=null,qr=null,ta=()=>{};function bs(){qr==null||qr(),qr=null}let na=()=>{var j;if(!Qn||!_t)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((j=e.ownerDocument.defaultView)!=null?j:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){_t.style.removeProperty("position"),_t.style.removeProperty("left"),_t.style.removeProperty("top"),_t.style.removeProperty("bottom"),_t.style.removeProperty("width"),_t.style.removeProperty("z-index");return}let x=Qn.firstElementChild;if(!x||x===_t)return;let C=10;_t.style.position="absolute",_t.style.top="0",_t.style.bottom="0",_t.style.width=`${C}px`,_t.style.zIndex="5";let k=x.offsetWidth-C/2;_t.style.left=`${Math.max(0,k)}px`},zo=()=>{},Er=()=>{var h,x,C,k,j;if(!wt||!sr(r))return;Yi(e,r),Zi(e,r),zo();let l=(k=(C=(x=(h=r.features)==null?void 0:h.artifacts)==null?void 0:x.layout)==null?void 0:C.narrowHostMaxWidth)!=null?k:520,m=Q.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),wt.update(On),Sn?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(j=wt.backdrop)==null||j.classList.add("persona-hidden")):On.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),ta()};if(sr(r)){Q.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Te),wt=Of(r,{onSelect:h=>{var x;return(x=Tt.current)==null?void 0:x.selectArtifact(h)},onDismiss:()=>{Sn=!0,Er()}}),wt.element.classList.add("persona-hidden"),Qn=m,m.appendChild(l),m.appendChild(wt.element),wt.backdrop&&Q.appendChild(wt.backdrop),Q.appendChild(m),ta=()=>{var x,C,k,j;if(!Qn||!wt)return;if(!(((k=(C=(x=r.features)==null?void 0:x.artifacts)==null?void 0:C.layout)==null?void 0:k.resizable)===!0)){Yn==null||Yn(),Yn=null,bs(),_t&&(_t.remove(),_t=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!_t){let O=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let N=e.ownerDocument,le=(j=N.defaultView)!=null?j:window,se=Z=>{var mt,at;if(!wt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||le.innerWidth<=640)return;Z.preventDefault(),bs();let we=Z.clientX,Fe=wt.element.getBoundingClientRect().width,_e=(at=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:at.layout,Ue=De=>{let We=Qn.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),Qe=Ve?0:jf(Qn,le),xt=Ve?0:O.getBoundingClientRect().width||6,R=Fe-(De.clientX-we),Ne=Uf(R,We,Qe,xt,_e==null?void 0:_e.resizableMinWidth,_e==null?void 0:_e.resizableMaxWidth);wt.element.style.width=`${Ne}px`,wt.element.style.maxWidth="none",na()},ze=()=>{N.removeEventListener("pointermove",Ue),N.removeEventListener("pointerup",ze),N.removeEventListener("pointercancel",ze),qr=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};qr=ze,N.addEventListener("pointermove",Ue),N.addEventListener("pointerup",ze),N.addEventListener("pointercancel",ze);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",se),_t=O,Qn.insertBefore(O,wt.element),Yn=()=>{O.removeEventListener("pointerdown",se)}}if(_t){let O=On.artifacts.length>0&&!Sn;_t.classList.toggle("persona-hidden",!O),na()}},zo=()=>{var le,se,Z,we,Fe,_e,Ue,ze,mt,at,De,We,Ve,Qe;if(!H||!wt||((se=(le=r.launcher)==null?void 0:le.sidebarMode)!=null?se:!1)||rn(r)&&Vn(r).reveal==="emerge")return;let x=(Z=e.ownerDocument.defaultView)!=null?Z:window,C=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,k=(Ue=(_e=r.launcher)==null?void 0:_e.mobileBreakpoint)!=null?Ue:640;if(C&&x.innerWidth<=k||!$f(r,H))return;let j=(at=(mt=(ze=r.launcher)==null?void 0:ze.width)!=null?mt:r.launcherWidth)!=null?at:zn,O=(Qe=(Ve=(We=(De=r.features)==null?void 0:De.artifacts)==null?void 0:We.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Sn?(Q.style.width=O,Q.style.maxWidth=O):(Q.style.width=j,Q.style.maxWidth=j)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{Er()}),Nn.observe(Q))}else Q.appendChild(Te),L()&&lt&&(Ke.peekBanner&&lt.appendChild(Ke.peekBanner),lt.appendChild(Be));e.appendChild(fe),lt&&e.appendChild(lt);let go=()=>{var Ne,He,Ze,It,$e,Jt,Ct,cn,Wn,Dt,hn,$n,Je,Rt,jn,Xo,Qo,Yo,Zo,ks,Ls,Xt,es,Co,Ao,Qr,ts,tt;if(L()){Q.style.width="100%",Q.style.maxWidth="100%";let Ot=(He=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?He:{},Nt=fe.dataset.state==="expanded",Kt=(Ze=Ot.expandedSize)!=null?Ze:"anchored";if(!(Nt&&Kt!=="fullscreen")){Te.style.background="",Te.style.border="",Te.style.borderRadius="",Te.style.overflow="",Te.style.boxShadow="";return}let gt=($e=(It=r.theme)==null?void 0:It.components)==null?void 0:$e.panel,Ut=zs(r),yn=(gn,nr)=>{var So;return gn==null||gn===""?nr:(So=Us(Ut,gn))!=null?So:gn},Un="1px solid var(--persona-border)",Hr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Te.style.background="var(--persona-surface, #ffffff)",Te.style.border=yn(gt==null?void 0:gt.border,Un),Te.style.borderRadius=yn(gt==null?void 0:gt.borderRadius,mn),Te.style.boxShadow=yn(gt==null?void 0:gt.shadow,Hr),Te.style.overflow="hidden";return}let l=rn(r),m=(Ct=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?Ct:!1,h=l||m||((Wn=(cn=r.launcher)==null?void 0:cn.fullHeight)!=null?Wn:!1),x=((Dt=r.launcher)==null?void 0:Dt.enabled)===!1,C=($n=(hn=r.theme)==null?void 0:hn.components)==null?void 0:$n.panel,k=zs(r),j=(Ot,Nt)=>{var Kt;return Ot==null||Ot===""?Nt:(Kt=Us(k,Ot))!=null?Kt:Ot},O=(Je=e.ownerDocument.defaultView)!=null?Je:window,N=(jn=(Rt=r.launcher)==null?void 0:Rt.mobileFullscreen)!=null?jn:!0,le=(Qo=(Xo=r.launcher)==null?void 0:Xo.mobileBreakpoint)!=null?Qo:640,se=O.innerWidth<=le,Z=N&&se&&H,we=(Zo=(Yo=r.launcher)==null?void 0:Yo.position)!=null?Zo:"bottom-left",Fe=we==="bottom-left"||we==="top-left",_e=(Ls=(ks=r.launcher)==null?void 0:ks.zIndex)!=null?Ls:Cn,Ue=m||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":m?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",Ue="none");let mt=m||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=j(C==null?void 0:C.border,Ue),De=j(C==null?void 0:C.shadow,ze),We=j(C==null?void 0:C.borderRadius,mt),Ve=Ce.scrollTop;e.style.cssText="",fe.style.cssText="",Q.style.cssText="",Te.style.cssText="",Ce.style.cssText="",Be.style.cssText="",X&&(Ce.style.display="none");let Qe=()=>{var Nt;if(Ve<=0)return;((Nt=Ce.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(Ce.scrollTop===Ve)return;let Kt=Ce.scrollHeight-Ce.clientHeight;Kt<=0||(Ce.scrollTop=Math.min(Ve,Kt))})};if(Z){fe.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"),fe.style.cssText=`
35
35
  position: fixed !important;
36
36
  inset: 0 !important;
37
37
  width: 100% !important;
@@ -67,7 +67,7 @@ _Details: ${n.message}_`:r}var Ta=e=>({isError:!0,content:[{type:"text",text:e}]
67
67
  overflow: hidden !important;
68
68
  border-radius: 0 !important;
69
69
  border: none !important;
70
- `,Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.overflowY="auto",Be.style.flexShrink="0",j=!0,Qe();return}let xt=(Yo=(Xt=r==null?void 0:r.launcher)==null?void 0:Xt.width)!=null?Yo:r==null?void 0:r.launcherWidth,B=xt!=null?xt:zn;if(!m&&!l)x&&h?(Q.style.width="100%",Q.style.maxWidth="100%"):(Q.style.width=B,Q.style.maxWidth=B);else if(l)if(Vn(r).reveal==="emerge"){let Nt=Vn(r).width;Q.style.width=Nt,Q.style.maxWidth=Nt}else Q.style.width="100%",Q.style.maxWidth="100%";if(Uo(),Q.style.boxShadow=De,Q.style.borderRadius=We,Te.style.border=at,Te.style.borderRadius=We,l&&!Z&&(S==null?void 0:S.border)===void 0&&(Te.style.border="none",Vn(r).side==="right"?Te.style.borderLeft="1px solid var(--persona-border)":Te.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",x&&(fe.style.overflow="hidden"),Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.height="100%",Q.style.overflow="hidden",Te.style.display="flex",Te.style.flexDirection="column",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.maxHeight="100%",Te.style.overflow="hidden",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.overflowY="auto",Be.style.flexShrink="0"),fe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!x&&!l&&((vo=xr[we])!=null?vo:xr["bottom-right"]).split(" ").forEach(Nt=>fe.classList.add(Nt)),m){let Ot=(Gr=(wo=r.launcher)==null?void 0:wo.sidebarWidth)!=null?Gr:"420px";fe.style.cssText=`
70
+ `,Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.overflowY="auto",Be.style.flexShrink="0",U=!0,Qe();return}let xt=(es=(Xt=r==null?void 0:r.launcher)==null?void 0:Xt.width)!=null?es:r==null?void 0:r.launcherWidth,R=xt!=null?xt:zn;if(!m&&!l)x&&h?(Q.style.width="100%",Q.style.maxWidth="100%"):(Q.style.width=R,Q.style.maxWidth=R);else if(l)if(Vn(r).reveal==="emerge"){let Nt=Vn(r).width;Q.style.width=Nt,Q.style.maxWidth=Nt}else Q.style.width="100%",Q.style.maxWidth="100%";if(zo(),Q.style.boxShadow=De,Q.style.borderRadius=We,Te.style.border=at,Te.style.borderRadius=We,l&&!Z&&(C==null?void 0:C.border)===void 0&&(Te.style.border="none",Vn(r).side==="right"?Te.style.borderLeft="1px solid var(--persona-border)":Te.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",x&&(fe.style.overflow="hidden"),Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.height="100%",Q.style.overflow="hidden",Te.style.display="flex",Te.style.flexDirection="column",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.maxHeight="100%",Te.style.overflow="hidden",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.overflowY="auto",Be.style.flexShrink="0"),fe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!x&&!l&&((Co=br[we])!=null?Co:br["bottom-right"]).split(" ").forEach(Nt=>fe.classList.add(Nt)),m){let Ot=(Qr=(Ao=r.launcher)==null?void 0:Ao.sidebarWidth)!=null?Qr:"420px";fe.style.cssText=`
71
71
  position: fixed !important;
72
72
  top: 0 !important;
73
73
  bottom: 0 !important;
@@ -108,23 +108,23 @@ _Details: ${n.message}_`:r}var Ta=e=>({isError:!0,content:[{type:"text",text:e}]
108
108
  flex-shrink: 0 !important;
109
109
  border-top: none !important;
110
110
  padding: 8px 16px 12px 16px !important;
111
- `}if(!x&&!l){let Ot="max-height: -moz-available !important; max-height: stretch !important;",Nt=m?"":"padding-top: 1.25em !important;",Kt=m?"":`z-index: ${(tt=(Zo=r.launcher)==null?void 0:Zo.zIndex)!=null?tt:vn} !important;`;fe.style.cssText+=Ot+Nt+Kt}Qe()};po(),Ro(e,r),Ki(e,r),Gi(e,r);let ct=[];ct.push(()=>{document.removeEventListener("keydown",Ur)}),ct.push(()=>{cr!==null&&clearTimeout(cr)});let sn=null,an=null;ct.push(()=>{sn==null||sn(),sn=null,an==null||an(),an=null}),Nn&&ct.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),ct.push(()=>{Yn==null||Yn(),Yn=null,hs(),_t&&(_t.remove(),_t=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),re&&ct.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),ke==null||ke.destroy(),ke=null,K==null||K.destroy(),K=null,ye=null});let kr=null,Zs=()=>{kr&&(kr(),kr=null),r.colorScheme==="auto"&&(kr=Si(()=>{Ro(e,r)}))};Zs(),ct.push(()=>{kr&&(kr(),kr=null)}),ct.push(a);let zr=(Zd=r.features)==null?void 0:Zd.streamAnimation;if(zr!=null&&zr.type&&zr.type!=="none"){let l=js(zr.type,zr.plugins);l&&(Wi(l,e),ct.push(()=>Zg(e)))}let qo=xf(zt),Lr=null,_,ys=l=>{var x,S;if(!_)return;let m=l!=null?l:_.getMessages(),h=((S=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:S.enabled)!==!1?oi(m):null;h?qo.render(h,_,xe,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(H=>H.role==="user")?qo.render([],_,xe,m):qo.render(r.suggestionChips,_,xe,m,r.suggestionChipsConfig)},pr=!1,Pr=$g(),Vr=new Map,Ir=new Map,ur=new Map,bs=0,qa=ns()!==null,yn=Mi(),An=0,mr=null,Sn=!1,zo=!1,gr=0,bn=null,Rr=null,xs=!1,Vo=!1,vs=null,uo=!0,mo=!1,st=null,w=4,V=24,z=80,J=new Map,G={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Oe=(tp=(ep=r.voiceRecognition)==null?void 0:ep.autoResume)!=null?tp:!1,ot=l=>{i.emit("voice:state",{active:G.active,source:l,timestamp:Date.now()})},dt=()=>{v(l=>({...l,voiceState:{active:G.active,timestamp:Date.now(),manuallyDeactivated:G.manuallyDeactivated}}))},pl=()=>{var x,S;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let l=hc(p.voiceState),m=!!l.active,h=Number((S=l.timestamp)!=null?S:0);G.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-h<Ox&&setTimeout(()=>{var H,q;G.active||(G.manuallyDeactivated=!1,((q=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:q.type)==="runtype"?_.toggleVoice().then(()=>{G.active=_.isVoiceActive(),ot("restore"),_.isVoiceActive()&&As()}):Va("restore"))},1e3)},go=()=>_?Of(_.getMessages()).filter(l=>!l.__skipPersist):[];function In(l){if(!(c!=null&&c.save))return;let h={messages:l?Of(l):_?go():[],metadata:p,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let x=c.save(h);x instanceof Promise&&x.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let Yt=null,fo=()=>fe.querySelector("#persona-scroll-container")||Ce,Zn=()=>{Yt!==null&&(cancelAnimationFrame(Yt),Yt=null),Sn=!1},Tn=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),zo=!1,Zn()},Rn=()=>pr&&ul()&&(Ft()!=="anchor-top"||ir()),En=()=>{let l=vt()||"Jump to latest",m=Rn();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),gr>0?(Bn.textContent=String(gr),Bn.style.display="",Vt.setAttribute("aria-label",`${l} (${gr} new)`)):(Bn.textContent="",Bn.style.display="none",Vt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},Hc=()=>{gr!==0&&(gr=0,En())},ul=()=>tn()?!yn.isFollowing():!Wo(Ce,V),_n=()=>{if(!Qt()||X){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==Te&&Te.appendChild(Vt),Gn();let m=Nr(Ce)>0&&ul();m?En():Hc(),Vt.style.display=m?"":"none"},ea=()=>{yn.pause()&&(Tn(),_n())},ho=()=>{yn.resume(),Hc(),_n()},yo=(l=!1)=>{tn()&&yn.isFollowing()&&(!l&&!pr||(mr!==null&&(cancelAnimationFrame(mr),mr=null),zo=!0,mr=requestAnimationFrame(()=>{mr=null,zo=!1,yn.isFollowing()&&Th(fo(),l?220:140)})))},Bc=(l,m,h,x=()=>!0)=>{let S=l.scrollTop,H=m(),q=H-S;if(Zn(),Math.abs(q)<1){Sn=!0,l.scrollTop=H,An=l.scrollTop,Sn=!1;return}let $=performance.now();Sn=!0;let N=se=>1-Math.pow(1-se,3),le=se=>{if(!x()){Zn();return}let Z=m();Z!==H&&(H=Z,q=H-S);let we=se-$,Fe=Math.min(we/h,1),_e=N(Fe),Ue=S+q*_e;l.scrollTop=Ue,An=l.scrollTop,Fe<1?Yt=requestAnimationFrame(le):(l.scrollTop=H,An=l.scrollTop,Yt=null,Sn=!1)};Yt=requestAnimationFrame(le)},Th=(l,m=500)=>{let h=Nr(l)-l.scrollTop;if(Math.abs(h)<1){An=l.scrollTop;return}if(Math.abs(h)>=z){Zn(),Sn=!0,l.scrollTop=Nr(l),An=l.scrollTop,Sn=!1;return}Bc(l,()=>Nr(l),m,()=>yn.isFollowing())},Dc=()=>{let l=fo();Sn=!0,l.scrollTop=Nr(l),An=l.scrollTop,Sn=!1,_n()},Nc=l=>{let m=0,h=l;for(;h&&h!==Ce;)m+=h.offsetTop,h=h.offsetParent;return m},Oc=()=>{var H;if(Fr()!=="last-user-turn")return!1;let l=(H=_==null?void 0:_.getMessages())!=null?H:[];if(l.length<2)return!1;let m=[...l].reverse().find(q=>q.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=Ce.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let S=Math.min(Math.max(0,Nc(x)-Cr()),Nr(Ce));return Sn=!0,Ce.scrollTop=S,An=Ce.scrollTop,Sn=!1,Ft()==="follow"&&!Wo(Ce,V)&&yn.pause(),_n(),!0},Fc=l=>{Ln.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},ta=()=>{Rr!==null&&(cancelAnimationFrame(Rr),Rr=null),Zn(),bn=null,Ln.style.height="0px"},Eh=l=>{Rr!==null&&cancelAnimationFrame(Rr),Rr=requestAnimationFrame(()=>{var N;Rr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=Ce.querySelector(`[data-message-id="${m}"]`);if(!h)return;let x=Nc(h),S=(N=bn==null?void 0:bn.spacerHeight)!=null?N:0,H=Ce.scrollHeight-S,{targetScrollTop:q,spacerHeight:$}=Vg({anchorOffsetTop:x,topOffset:Cr(),viewportHeight:Ce.clientHeight,contentHeight:H});bn={initialSpacerHeight:$,contentHeightAtAnchor:H,spacerHeight:$},Fc($),Bc(Ce,()=>q,220)})},Mh=()=>{if(tn()){if(!yn.isFollowing()||Wo(Ce,1))return;yo(!pr);return}if(bn&&bn.initialSpacerHeight>0){let l=Ce.scrollHeight-bn.spacerHeight,m=Kg({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});m!==bn.spacerHeight&&Fc(m)}_n()},kh=l=>{let m=Ft();m==="follow"?(ho(),yo(!0)):m==="anchor-top"&&(uo=!1,mo=!0,Eh(l))},Lh=()=>{if(Ft()==="anchor-top"){if(mo){uo=!1;return}uo=!0,ta(),ho(),yo(!0)}},Ph=l=>{let m=new Map;l.forEach(h=>{let x=J.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Vo&&(Ft()!=="anchor-top"||ir())&&ul()&&(gr+=1,En(),_n(),ro(gr===1?"1 new message below.":`${gr} new messages below.`))),h.role==="assistant"&&(x!=null&&x.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),J.clear(),m.forEach((h,x)=>{J.set(x,h)})},Ih=(l,m,h)=>{var at,De,We,Ve,Qe,xt;let x=document.createElement("div"),H=(()=>{var Ne;let B=o.find(He=>He.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),q=(B,Ne)=>Ne==null?!1:typeof Ne=="string"?(B.textContent=Ne,!0):(B.appendChild(Ne),!0),$=new Set,N=new Set,le=o.some(B=>B.renderAskUserQuestion),se=[],Z=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,_e=[];if(m.forEach(B=>{var gn,$n,Je,Rt,jn,Go,Jo,Xo,Qo,Ts,Es,Xt,Yo,vo,wo,Gr,Zo;$.add(B.id);let Ne=le&&Jr(B),He=Fe&&B.variant==="approval"&&!!B.approval,Ze=!Ne&&B.role==="assistant"&&!B.variant&&we&&Yi(B);if(!He&&ur.has(B.id)){let tt=l.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),ur.delete(B.id)}if(!Ze&&Ir.has(B.id)){let tt=l.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),Ir.delete(B.id)}let It=Jr(B)?`:${(gn=B.agentMetadata)!=null&&gn.askUserQuestionAnswered?"a":"u"}:${($n=B.agentMetadata)!=null&&$n.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",$e=_g(B,bs)+It,Jt=Ne||He||Ze?null:jg(Pr,B.id,$e);if(Jt){x.appendChild(Jt.cloneNode(!0)),Jr(B)&&((Je=B.toolCall)!=null&&Je.id)&&((Rt=B.agentMetadata)==null?void 0:Rt.awaitingLocalTool)===!0&&!((jn=B.agentMetadata)!=null&&jn.askUserQuestionAnswered)&&(N.add(B.toolCall.id),Hs(B,r,Ke.composerOverlay));return}let Ct=null,cn=o.find(tt=>!!(B.variant==="reasoning"&&tt.renderReasoning||B.variant==="tool"&&tt.renderToolCall||!B.variant&&tt.renderMessage)),Wn=(Go=r.layout)==null?void 0:Go.messages;if(Jr(B)&&((Jo=B.agentMetadata)==null?void 0:Jo.askUserQuestionAnswered)===!0){Vr.delete(B.id);let tt=l.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime");return}if(ya(B)&&((Qo=(Xo=r.features)==null?void 0:Xo.suggestReplies)==null?void 0:Qo.enabled)!==!1)return;if(Jr(B)&&((Es=(Ts=r.features)==null?void 0:Ts.askUserQuestion)==null?void 0:Es.enabled)!==!1){let tt=o.find(Ot=>typeof Ot.renderAskUserQuestion=="function");if(tt&&Tt.current){let Ot=Vr.get(B.id),Nt=Ot!==$e,Kt=null;if(Nt){let{payload:Ut,complete:fn}=Xr(B),Un=B.id,Hr=()=>{var un;return(un=Tt.current)==null?void 0:un.getMessages().find(mn=>mn.id===Un)};Kt=tt.renderAskUserQuestion({message:B,payload:Ut,complete:fn,resolve:un=>{var nr;let mn=Hr();mn&&((nr=Tt.current)==null||nr.resolveAskUserQuestion(mn,un))},dismiss:()=>{var mn,nr,Co;let un=Hr();(mn=un==null?void 0:un.agentMetadata)!=null&&mn.awaitingLocalTool&&((nr=Tt.current)==null||nr.markAskUserQuestionResolved(un),(Co=Tt.current)==null||Co.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let jt=Ot!=null;if(Nt&&Kt===null&&!jt){((Xt=B.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((Yo=B.agentMetadata)!=null&&Yo.askUserQuestionAnswered)&&(N.add(B.toolCall.id),Hs(B,r,Ke.composerOverlay));return}let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${B.id}`,gt.setAttribute("data-wrapper-id",B.id),gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),x.appendChild(gt),se.push({messageId:B.id,fingerprint:$e,bubble:Kt});return}else{((vo=B.agentMetadata)==null?void 0:vo.awaitingLocalTool)===!0&&!((wo=B.agentMetadata)!=null&&wo.askUserQuestionAnswered)&&(N.add(B.toolCall.id),Hs(B,r,Ke.composerOverlay));return}}else if(He){let tt=(Gr=o.find(jt=>typeof jt.renderApproval=="function"))!=null?Gr:s,Nt=ur.get(B.id)!==$e,Kt=null;if(Nt&&(tt!=null&&tt.renderApproval)){let jt=B.id,gt=(Ut,fn)=>{var Hr,un,mn;let Un=(Hr=Tt.current)==null?void 0:Hr.getMessages().find(nr=>nr.id===jt);Un!=null&&Un.approval&&(Un.approval.toolType==="webmcp"?(un=Tt.current)==null||un.resolveWebMcpApproval(Un.id,Ut):(mn=Tt.current)==null||mn.resolveApproval(Un.approval,Ut,fn))};Kt=tt.renderApproval({message:B,defaultRenderer:()=>zi(B,r),config:r,approve:Ut=>gt("approved",Ut),deny:Ut=>gt("denied",Ut)})}if(Nt&&Kt===null){let jt=l.querySelector(`#wrapper-${B.id}`);jt==null||jt.removeAttribute("data-preserve-runtime"),ur.delete(B.id),Ct=zi(B,r)}else{let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-${B.id}`,jt.setAttribute("data-wrapper-id",B.id),jt.setAttribute("data-approval-plugin-stub","true"),jt.setAttribute("data-preserve-runtime","true"),x.appendChild(jt),_e.push({messageId:B.id,fingerprint:$e,bubble:Kt});return}}else if(cn)if(B.variant==="reasoning"&&B.reasoning&&cn.renderReasoning){if(!Pe)return;Ct=cn.renderReasoning({message:B,defaultRenderer:()=>ac(B,r),config:r})}else if(B.variant==="tool"&&B.toolCall&&cn.renderToolCall){if(!Ie)return;Ct=cn.renderToolCall({message:B,defaultRenderer:()=>lc(B,r),config:r})}else cn.renderMessage&&(Ct=cn.renderMessage({message:B,defaultRenderer:()=>{let tt=zs(B,h,Wn,r.messageActions,be,{loadingIndicatorRenderer:H,widgetConfig:r});return B.role!=="user"&&mc(tt,B,r,_),tt},config:r}));if(!Ct&&Ze){let tt=Zi(B);if(tt){let Ot=Ir.get(B.id),Nt=Ot!==$e,Kt=r.wrapComponentDirectiveInBubble!==!1,jt=null;if(Nt){let gt=Qi(tt,{config:r,message:B,transform:h});if(gt)if(Kt){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${B.id}`,Ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let fn=document.createElement("div");fn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",fn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ut.appendChild(fn)}Ut.appendChild(gt),jt=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${B.id}`,Ut.setAttribute("data-message-id",B.id),Ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let fn=document.createElement("div");fn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",fn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ut.appendChild(fn)}Ut.appendChild(gt),jt=Ut}}if(jt||Ot!=null){let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${B.id}`,gt.setAttribute("data-wrapper-id",B.id),gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),Kt||gt.classList.add("persona-w-full"),x.appendChild(gt),Z.push({messageId:B.id,fingerprint:$e,bubble:jt});return}}}if(!Ct)if(B.variant==="reasoning"&&B.reasoning){if(!Pe)return;Ct=ac(B,r)}else if(B.variant==="tool"&&B.toolCall){if(!Ie)return;Ct=lc(B,r)}else if(B.variant==="approval"&&B.approval){if(r.approval===!1)return;Ct=zi(B,r)}else{let tt=(Zo=r.layout)==null?void 0:Zo.messages;tt!=null&&tt.renderUserMessage&&B.role==="user"?Ct=tt.renderUserMessage({message:B,config:r,streaming:!!B.streaming}):tt!=null&&tt.renderAssistantMessage&&B.role==="assistant"?Ct=tt.renderAssistantMessage({message:B,config:r,streaming:!!B.streaming}):Ct=zs(B,h,tt,r.messageActions,be,{loadingIndicatorRenderer:H,widgetConfig:r}),B.role!=="user"&&Ct&&mc(Ct,B,r,_)}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${B.id}`,Dt.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Dt.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&Dt.classList.add("persona-w-full"),Dt.appendChild(Ct),Ug(Pr,B.id,$e,Dt),x.appendChild(Dt)}),Ke.composerOverlay&&Ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let He=Ne.getAttribute("data-persona-ask-sheet-for");He&&!N.has(He)&&Eo(Ke.composerOverlay,He)}),(De=(at=r.features)==null?void 0:at.toolCallDisplay)!=null&&De.grouped){let B=[],Ne=[];m.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&Ie){Ne.push(He);return}Ne.length>1&&B.push(Ne),Ne=[]}),Ne.length>1&&B.push(Ne),B.forEach((He,Ze)=>{var gn,$n;let It=He.map(Je=>Array.from(x.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Je.id)).filter(Je=>!!Je);if(It.length<2)return;let $e=document.createElement("div");$e.className="persona-flex",$e.id=`wrapper-tool-group-${Ze}-${He[0].id}`,$e.setAttribute("data-wrapper-id",`tool-group-${Ze}-${He[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${He.length} tools`,Wn=($n=(gn=r.toolCall)==null?void 0:gn.renderGroupedSummary)==null?void 0:$n.call(gn,{messages:He,toolCalls:He.map(Je=>Je.toolCall).filter(Je=>!!Je),defaultSummary:cn,config:r});q(Ct,Wn)||(Ct.textContent=cn);let Dt=document.createElement("div");Dt.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,Dt),$e.appendChild(Jt),It[0].before($e),It.forEach((Je,Rt)=>{let jn=document.createElement("div");jn.className="persona-tool-group-item persona-relative",jn.setAttribute("data-persona-tool-group-item","true"),Rt<It.length-1&&jn.setAttribute("data-persona-tool-group-connector","true"),jn.appendChild(Je),Dt.appendChild(jn)})})}qg(Pr,$);let Ue=m.some(B=>B.role==="assistant"&&B.streaming),ze=m[m.length-1],mt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(pr&&m.some(B=>B.role==="user")&&!Ue&&!mt){let B={config:r,streaming:!0,location:"standalone",defaultRenderer:ds},Ne=o.find(Ze=>Ze.renderLoadingIndicator),He=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(He=Ne.renderLoadingIndicator(B)),He===null&&((We=r.loadingIndicator)!=null&&We.render)&&(He=r.loadingIndicator.render(B)),He===null&&(He=ds()),He){let Ze=document.createElement("div"),It=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;Ze.className=It?["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(" "),Ze.setAttribute("data-typing-indicator","true"),Ze.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ze.appendChild(He);let $e=document.createElement("div");$e.className="persona-flex",$e.id="wrapper-typing-indicator",$e.setAttribute("data-wrapper-id","typing-indicator"),$e.appendChild(Ze),x.appendChild($e)}}if(!pr&&m.length>0){let B=m[m.length-1],Ne={config:r,lastMessage:B,messageCount:m.length},He=o.find(It=>It.renderIdleIndicator),Ze=null;if(He!=null&&He.renderIdleIndicator&&(Ze=He.renderIdleIndicator(Ne)),Ze===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(Ze=r.loadingIndicator.renderIdle(Ne)),Ze){let It=document.createElement("div"),$e=((xt=r.loadingIndicator)==null?void 0:xt.showBubble)!==!1;It.className=$e?["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(" "),It.setAttribute("data-idle-indicator","true"),It.appendChild(Ze);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(It),x.appendChild(Jt)}}if(Ti(l,x),se.length>0)for(let{messageId:B,fingerprint:Ne,bubble:He}of se){let Ze=l.querySelector(`#wrapper-${B}`);Ze&&He!==null&&(Ze.replaceChildren(He),Ze.setAttribute("data-bubble-fp",Ne),Vr.set(B,Ne))}if(Vr.size>0)for(let B of Vr.keys())$.has(B)||Vr.delete(B);if(Z.length>0)for(let{messageId:B,fingerprint:Ne,bubble:He}of Z){let Ze=l.querySelector(`#wrapper-${B}`);Ze&&He!==null&&(Ze.replaceChildren(He),Ze.setAttribute("data-bubble-fp",Ne),Ir.set(B,Ne))}if(Ir.size>0)for(let B of Ir.keys())$.has(B)||Ir.delete(B);if(_e.length>0)for(let{messageId:B,fingerprint:Ne,bubble:He}of _e){let Ze=l.querySelector(`#wrapper-${B}`);Ze&&He!==null&&(Ze.replaceChildren(He),Ze.setAttribute("data-bubble-fp",Ne),ur.set(B,Ne))}if(ur.size>0)for(let B of ur.keys())$.has(B)||ur.delete(B)},na=(l,m,h)=>{Ih(l,m,h),lo()},ra=null,Rh=()=>{var h;if(ra)return;let l=x=>{let S=x.composedPath();S.includes(fe)||lt&&S.includes(lt)||$t(!1,"user")};ra=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},_c=()=>{var m;if(!ra)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",ra,!0),ra=null};ct.push(()=>_c());let oa=null,Wh=()=>{var h;if(oa)return;let l=x=>{x.key==="Escape"&&(x.isComposing||$t(!1,"user"))};oa=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},$c=()=>{var m;if(!oa)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",oa,!0),oa=null};ct.push(()=>$c());let sa=!1,jc=new Set,Hh=()=>{var m,h,x,S;let l=(x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:x.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},ws=()=>{var mt,at,De,We;if(!W())return;let l=Ke.peekBanner,m=Ke.peekTextNode;if(!l||!m)return;if(F){l.classList.remove("persona-pill-peek--visible");return}let h=(mt=_==null?void 0:_.getMessages())!=null?mt:[],x;for(let Ve=h.length-1;Ve>=0;Ve--){let Qe=h[Ve];if(Qe.role==="assistant"&&Qe.content){x=Qe;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let S=x.content,H=!!x.streaming,q=Hh(),$=Pi(q),N=$.type!=="none"?js($.type,q==null?void 0:q.plugins):null,le=((at=N==null?void 0:N.isAnimating)==null?void 0:at.call(N,x))===!0,se=N!==null&&(H||le);se&&N&&!jc.has(N.name)&&(Wi(N,e),jc.add(N.name));let Z=se&&(N!=null&&N.containerClass)?N.containerClass:null,we=(De=m.dataset.personaPeekStreamClass)!=null?De:null;we&&we!==Z&&(m.classList.remove(we),delete m.dataset.personaPeekStreamClass),Z&&we!==Z&&(m.classList.add(Z),m.dataset.personaPeekStreamClass=Z),se?(m.style.setProperty("--persona-stream-step",`${$.speed}ms`),m.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Fe=se?Ii(S,$.buffer,N,x,H):S;if(se&&$.placeholder==="skeleton"&&H&&(!Fe||!Fe.trim())){let Ve=document.createElement("div"),Qe=Ia();Qe.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Qe),Ti(m,Ve)}else{let Ve=Math.max(0,Fe.length-100),Qe=Fe.length>100?Fe.slice(-100):Fe,xt=Br(Qe);if(!se||!N){let B=Fe.length>100?`\u2026${Qe}`:Qe;m.textContent!==B&&(m.textContent=B)}else{let B=xt;(N.wrap==="char"||N.wrap==="word")&&(B=Pa(xt,N.wrap,`peek-${x.id}`,{skipTags:N.skipTags,startIndex:Ve}));let Ne=document.createElement("div");if(Ne.innerHTML=B,N.useCaret&&Qe.length>0){let He=Ri(),Ze=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),It=Ze[Ze.length-1];It!=null&&It.parentNode?It.parentNode.insertBefore(He,It.nextSibling):Ne.appendChild(He)}Ti(m,Ne),(We=N.onAfterRender)==null||We.call(N,{container:m,bubble:l,messageId:x.id,message:x,speed:$.speed,duration:$.duration})}}let ze=pr||sa;l.classList.toggle("persona-pill-peek--visible",ze)};if(W()){let l=Ke.peekBanner;if(l){let x=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",x),ct.push(()=>{l.removeEventListener("pointerdown",x)})}let m=()=>{sa||(sa=!0,ws())},h=()=>{sa&&(sa=!1,ws())};Q.addEventListener("pointerenter",m),Q.addEventListener("pointerleave",h),ct.push(()=>{Q.removeEventListener("pointerenter",m),Q.removeEventListener("pointerleave",h)}),lt&&(lt.addEventListener("pointerenter",m),lt.addEventListener("pointerleave",h),ct.push(()=>{lt.removeEventListener("pointerenter",m),lt.removeEventListener("pointerleave",h)}))}let Bh=l=>{var we,Fe,_e,Ue,ze,mt,at,De;let m=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(_e=m.expandedSize)!=null?_e:"anchored",x=(Ue=m.bottomOffset)!=null?Ue:"16px",S=m.collapsedMaxWidth,H=(ze=m.expandedMaxWidth)!=null?ze:"880px",q=(mt=m.expandedTopOffset)!=null?mt:"5vh",$=(at=m.modalMaxWidth)!=null?at:"880px",N=(De=m.modalMaxHeight)!=null?De:"min(90vh, 800px)",le="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Z=fe.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",lt){let We=lt.style;We.bottom=x,We.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=$,Z.maxWidth=le,Z.maxHeight=N,Z.height=N;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${x} + ${se})`,Z.top=q,Z.width=H,Z.maxWidth=le}},aa=()=>{var N,le,se,Z,we,Fe,_e,Ue;if(!O())return;if(W()){let mt=(se=((le=(N=r.launcher)==null?void 0:N.composerBar)!=null?le:{}).expandedSize)!=null?se:"anchored",at=F?"expanded":"collapsed";fe.dataset.state=at,fe.dataset.expandedSize=mt,lt&&(lt.dataset.state=at,lt.dataset.expandedSize=mt),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Bh(F),Te.style.display=F?"flex":"none",po(),F?(Rh(),Wh()):(_c(),$c()),ws();return}let l=on(r),m=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,x=(Ue=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ue:!0,S=m.innerWidth<=h,H=x&&S&&I,q=Vn(r).reveal;F?(fe.style.removeProperty("display"),fe.style.display=l?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0"),Q.classList.add("persona-scale-100","persona-opacity-100"),en?en.element.style.display="none":ln&&(ln.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!H?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100"),Q.classList.add("persona-scale-95","persona-opacity-0")),en?en.element.style.display=l?"none":"":ln&&(ln.style.display=l?"none":""))},$t=(l,m="user")=>{var H,q;if(!O()||F===l)return;let h=F;F=l,aa();let x=(()=>{var _e,Ue,ze,mt,at,De,We,Ve,Qe,xt;let $=(Ue=(_e=r.launcher)==null?void 0:_e.sidebarMode)!=null?Ue:!1,N=(ze=e.ownerDocument.defaultView)!=null?ze:window,le=(at=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?at:!0,se=(We=(De=r.launcher)==null?void 0:De.mobileBreakpoint)!=null?We:640,Z=N.innerWidth<=se,we=on(r)&&le&&Z,Fe=W()&&((xt=(Qe=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return $||le&&Z&&I||we||Fe})();if(F&&x){if(!sn){let $=e.getRootNode(),N=$ instanceof ShadowRoot?$.host:e.closest(".persona-host");N&&(sn=Jl(N,(q=(H=r.launcher)==null?void 0:H.zIndex)!=null?q:vn))}an||(an=Xl(e.ownerDocument))}else F||(sn==null||sn(),sn=null,an==null||an(),an=null);F&&(ia(),Oc()||(Ft()==="follow"?yo(!0):Dc()));let S={open:F,source:m,timestamp:Date.now()};F&&!h?i.emit("widget:opened",S):!F&&h&&i.emit("widget:closed",S),i.emit("widget:state",{open:F,launcherEnabled:I,voiceActive:G.active,streaming:_.isStreaming()})},ml=l=>{ge(l?"stop":"send"),D&&(D.disabled=l),qo.buttons.forEach(m=>{m.disabled=l}),Be.dataset.personaComposerStreaming=l?"true":"false",Be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},gl=()=>{G.active||xe&&xe.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>gl(),200)});let Uc=()=>{var h,x,S,H,q,$,N,le,se,Z,we;vr.textContent=(x=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?x:"Hello \u{1F44B}",wr.textContent=(H=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",xe.placeholder=($=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?$:"How can I help...";let l=Ce.querySelector("[data-persona-intro-card]");if(l){let Fe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Ce.classList.remove("persona-gap-3"),Ce.classList.add("persona-gap-6")):(Ce.classList.remove("persona-gap-6"),Ce.classList.add("persona-gap-3"))}!((se=(le=r.sendButton)==null?void 0:le.useIcon)!=null&&se)&&!(_!=null&&_.isStreaming())&&(ue.textContent=(we=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?we:"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(m=>({...m,sessionId:l}))}});let Ko=null,Dh=()=>{Ko==null&&(Ko=setInterval(()=>{let l=et.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ko),Ko=null;return}let m=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=ai(m-x))})},100))};_=new Os(r,{onMessagesChanged(l){var S,H;na(et,l,te),Dh(),ys(l),yo(!pr),Ph(l);let m=[...l].reverse().find(q=>q.role==="user"),h=[...l].reverse().find(q=>q.role==="assistant");l.length===0&&(ta(),uo=!0,mo=!1),!xs||Vo?(xs=!0,vs=(S=m==null?void 0:m.id)!=null?S:null,st=(H=h==null?void 0:h.id)!=null?H:null):m&&m.id!==vs?(vs=m.id,kh(m.id)):h&&h.id!==st&&Lh(),h&&(st=h.id);let x=G.lastUserMessageId;m&&m.id!==x&&(G.lastUserMessageId=m.id,i.emit("user:message",m)),G.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),In(l),ws()},onStatusChanged(l){var x;let m=(x=r.statusIndicator)!=null?x:{};Ht(hn,(S=>{var H,q,$,N,le,se;return S==="idle"?(H=m.idleText)!=null?H:rn.idle:S==="connecting"?(q=m.connectingText)!=null?q:rn.connecting:S==="connected"?($=m.connectedText)!=null?$:rn.connected:S==="error"?(N=m.errorText)!=null?N:rn.error:S==="paused"?(le=m.pausedText)!=null?le:rn.paused:S==="resuming"?(se=m.resumingText)!=null?se:rn.resuming:rn[S]})(l),m,l)},onStreamingChanged(l){pr=l,ml(l),_&&na(et,_.getMessages(),te),l||yo(!0),_n(),ro(l?"Responding\u2026":"Response complete."),ws()},onVoiceStatusChanged(l){var m,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Kr(),As();break;case"processing":Kr(),$h();break;case"speaking":Kr(),jh();break;default:l==="idle"&&_.isBargeInActive()?(Kr(),As(),D==null||D.setAttribute("aria-label","End voice session")):(G.active=!1,Kr(),ot("system"),dt());break}},onArtifactsState(l){On=l,Mr(),In()},onReconnect(l){var x;let{executionId:m,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:h,attempt:(x=l.attempt)!=null?x:1}):i.emit("stream:resumed",{executionId:m,after:h})}}),Tt.current=_,ct.push(()=>_.cancel());let fl=null;if(_.onReadAloudChange((l,m)=>{var S;ao=l,io=m,lo();let h=l!=null?l:fl;l&&(fl=l);let x=h&&(S=_.getMessages().find(H=>H.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:x,state:m,timestamp:Date.now()}),m==="idle"&&(fl=null)}),xs=!0,((rp=(np=r.voiceRecognition)==null?void 0:np.provider)==null?void 0:rp.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(K||r.onSSEEvent)&&_.setSSEEventCallback((l,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,m),Y==null||Y.processEvent(l,m),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let qc=()=>{r.resume&&typeof r.reconnectStream=="function"&&_.resumeFromHandle(r.resume)};u?u.then(l=>{var m,h,x;if(l){if(l.metadata&&(p=hc(l.metadata),P.syncFromMetadata()),(m=l.messages)!=null&&m.length){Vo=!0;try{_.hydrateMessages(l.messages)}finally{Vo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(x=l.selectedArtifactId)!=null?x:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>qc()):qc();let zc=()=>{var m,h,x;!W()||F||!((x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||x)||$t(!0,"auto")},Vc=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),Y==null||Y.reset(),ke==null||ke.update();return}let m=xe.value.trim(),h=(S=St==null?void 0:St.hasAttachments())!=null?S:!1;if(!m&&!h)return;zc();let x;h&&(x=[],x.push(...St.getContentParts()),m&&x.push(Ca(m))),xe.value="",xe.style.height="auto",za(),_.sendMessage(m,{contentParts:x}),h&&St.clearAttachments()},Nh=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},hl={...Ei},yl=!1,za=()=>{hl={...Ei}},Oh=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),Fh=l=>{if(!xe)return;yl=!0,xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),yl=!1;let m=xe.value.length;xe.setSelectionRange(m,m)},Kc=()=>{yl||za()},Gc=l=>{if(xe){if(Nh()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=xe.selectionStart===0&&xe.selectionEnd===0,h=Fg({direction:l.key==="ArrowUp"?"up":"down",history:Oh(),currentValue:xe.value,atStart:m,state:hl});if(hl=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Fh(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}za(),l.preventDefault(),ue.click()}}},Jc=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(Te)&&(_.cancel(),Y==null||Y.reset(),ke==null||ke.update(),za(),l.preventDefault(),l.stopImmediatePropagation())},Xc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!St)return;let m=_x(l.clipboardData);m.length!==0&&(l.preventDefault(),await St.handleFiles(m))},er=null,Wr=!1,Cs=null,ut=null,Qc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Va=(l="user")=>{var H,q,$,N,le,se,Z;if(Wr||_.isStreaming())return;let m=Qc();if(!m)return;er=new m;let x=(q=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?q:2e3;er.continuous=!0,er.interimResults=!0,er.lang="en-US";let S=xe.value;er.onresult=we=>{let Fe="",_e="";for(let ze=0;ze<we.results.length;ze++){let mt=we.results[ze],at=mt[0].transcript;mt.isFinal?Fe+=at+" ":_e=at}let Ue=S+Fe+_e;xe.value=Ue,Cs&&clearTimeout(Cs),(Fe||_e)&&(Cs=window.setTimeout(()=>{let ze=xe.value.trim();ze&&er&&Wr&&(bo(),xe.value="",xe.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},x))},er.onerror=we=>{we.error!=="no-speech"&&bo()},er.onend=()=>{if(Wr){let we=xe.value.trim();we&&we!==S.trim()&&(xe.value="",xe.style.height="auto",_.sendMessage(we,{viaVoice:!0})),bo()}};try{if(er.start(),Wr=!0,G.active=!0,l!=="system"&&(G.manuallyDeactivated=!1),ot(l),dt(),D){let we=($=r.voiceRecognition)!=null?$:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(N=we.iconName)!=null?N:"mic",iconSize:parseFloat((Z=(se=we.iconSize)!=null?se:(le=r.sendButton)==null?void 0:le.size)!=null?Z:"40")||24};let Fe=we.recordingBackgroundColor,_e=we.recordingIconColor,Ue=we.recordingBorderColor;if(D.classList.add("persona-voice-recording"),D.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=_e!=null?_e:"var(--persona-voice-recording-indicator, #ffffff)",_e){let ze=D.querySelector("svg");ze&&ze.setAttribute("stroke",_e)}Ue&&(D.style.borderColor=Ue),D.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(l="user")=>{if(Wr){if(Wr=!1,Cs&&(clearTimeout(Cs),Cs=null),er){try{er.stop()}catch{}er=null}if(G.active=!1,ot(l),dt(),D){if(D.classList.remove("persona-voice-recording"),ut){D.style.backgroundColor=ut.backgroundColor,D.style.color=ut.color,D.style.borderColor=ut.borderColor;let m=D.querySelector("svg");m&&m.setAttribute("stroke",ut.color||"currentColor"),ut=null}D.setAttribute("aria-label","Start voice recognition")}}},_h=(l,m)=>{var at,De,We,Ve,Qe,xt,B,Ne,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((at=l==null?void 0:l.provider)==null?void 0:at.type)==="runtype",S=((De=l==null?void 0:l.provider)==null?void 0:De.type)==="custom";if(!(h||x||S))return null;let q=y("div","persona-send-button-wrapper"),$=y("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 N=(We=l==null?void 0:l.iconName)!=null?We:"mic",le=(Ve=m==null?void 0:m.size)!=null?Ve:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:le,Z=parseFloat(se)||24,we=(xt=l==null?void 0:l.backgroundColor)!=null?xt:m==null?void 0:m.backgroundColor,Fe=(B=l==null?void 0:l.iconColor)!=null?B:m==null?void 0:m.textColor;$.style.width=se,$.style.height=se,$.style.minWidth=se,$.style.minHeight=se,$.style.fontSize="18px",$.style.lineHeight="1",Fe?$.style.color=Fe:$.style.color="var(--persona-text, #111827)";let Ue=he(N,Z,Fe||"currentColor",1.5);Ue?$.appendChild(Ue):$.textContent="\u{1F3A4}",we?$.style.backgroundColor=we:$.style.backgroundColor="",l!=null&&l.borderWidth&&($.style.borderWidth=l.borderWidth,$.style.borderStyle="solid"),l!=null&&l.borderColor&&($.style.borderColor=l.borderColor),l!=null&&l.paddingX&&($.style.paddingLeft=l.paddingX,$.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&($.style.paddingTop=l.paddingY,$.style.paddingBottom=l.paddingY),q.appendChild($);let ze=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((He=l==null?void 0:l.showTooltip)!=null?He:!1)&&ze){let Ze=y("div","persona-send-button-tooltip");Ze.textContent=ze,q.appendChild(Ze)}return{micButton:$,micButtonWrapper:q}},bl=()=>{var m,h,x,S,H;if(!D||ut)return;let l=(m=r.voiceRecognition)!=null?m:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((H=(S=l.iconSize)!=null?S:(x=r.sendButton)==null?void 0:x.size)!=null?H:"40")||24}},xl=(l,m)=>{var H,q,$,N,le;if(!D)return;let h=D.querySelector("svg");h&&h.remove();let x=(le=ut==null?void 0:ut.iconSize)!=null?le:parseFloat((N=($=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?$:(q=r.sendButton)==null?void 0:q.size)!=null?N:"40")||24,S=he(l,x,m,1.5);S&&D.appendChild(S)},Ka=()=>{D&&D.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},As=()=>{var S;if(!D)return;bl();let l=(S=r.voiceRecognition)!=null?S:{},m=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Ka(),D.classList.add("persona-voice-recording"),D.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let H=D.querySelector("svg");H&&H.setAttribute("stroke",h)}x&&(D.style.borderColor=x),D.setAttribute("aria-label","Stop voice recognition")},$h=()=>{var $,N,le,se,Z,we,Fe,_e;if(!D)return;bl();let l=($=r.voiceRecognition)!=null?$:{},m=_.getVoiceInterruptionMode(),h=(N=l.processingIconName)!=null?N:"loader",x=(se=(le=l.processingIconColor)!=null?le:ut==null?void 0:ut.color)!=null?se:"",S=(we=(Z=l.processingBackgroundColor)!=null?Z:ut==null?void 0:ut.backgroundColor)!=null?we:"",H=(_e=(Fe=l.processingBorderColor)!=null?Fe:ut==null?void 0:ut.borderColor)!=null?_e:"";Ka(),D.classList.add("persona-voice-processing"),D.style.backgroundColor=S,D.style.borderColor=H;let q=x||"currentColor";D.style.color=q,xl(h,q),D.setAttribute("aria-label","Processing voice input"),m==="none"&&(D.style.cursor="default")},jh=()=>{var le,se,Z,we,Fe,_e,Ue,ze,mt,at,De,We;if(!D)return;bl();let l=(le=r.voiceRecognition)!=null?le:{},m=_.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(se=l.speakingIconName)!=null?se:h,S=(_e=l.speakingIconColor)!=null?_e:m==="barge-in"?(we=(Z=l.recordingIconColor)!=null?Z:ut==null?void 0:ut.color)!=null?we:"":(Fe=ut==null?void 0:ut.color)!=null?Fe:"",H=(mt=l.speakingBackgroundColor)!=null?mt:m==="barge-in"?(Ue=l.recordingBackgroundColor)!=null?Ue:"var(--persona-voice-recording-bg, #ef4444)":(ze=ut==null?void 0:ut.backgroundColor)!=null?ze:"",q=(We=l.speakingBorderColor)!=null?We:m==="barge-in"?(at=l.recordingBorderColor)!=null?at:"":(De=ut==null?void 0:ut.borderColor)!=null?De:"";Ka(),D.classList.add("persona-voice-speaking"),D.style.backgroundColor=H,D.style.borderColor=q;let $=S||"currentColor";D.style.color=$,xl(x,$);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";D.setAttribute("aria-label",N),m==="none"&&(D.style.cursor="default"),m==="barge-in"&&D.classList.add("persona-voice-recording")},Kr=()=>{var l,m,h;D&&(Ka(),ut&&(D.style.backgroundColor=(l=ut.backgroundColor)!=null?l:"",D.style.color=(m=ut.color)!=null?m:"",D.style.borderColor=(h=ut.borderColor)!=null?h:"",xl(ut.iconName,ut.color||"currentColor"),ut=null),D.style.cursor="",D.setAttribute("aria-label","Start voice recognition"))},Ga=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let h=_.getVoiceStatus(),x=_.getVoiceInterruptionMode();if(x==="none"&&(h==="processing"||h==="speaking"))return;if(x==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),ot("user"),Kr()});return}_.toggleVoice().then(()=>{G.active=_.isVoiceActive(),G.manuallyDeactivated=!_.isVoiceActive(),dt(),ot("user"),_.isVoiceActive()?As():Kr()});return}if(Wr){let h=xe.value.trim();G.manuallyDeactivated=!0,dt(),bo("user"),h&&(xe.value="",xe.style.height="auto",_.sendMessage(h))}else G.manuallyDeactivated=!1,dt(),Va("user")};Sr=Ga,D&&(D.addEventListener("click",Ga),ct.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Kr()):bo("system"),D&&D.removeEventListener("click",Ga)}));let Uh=i.on("assistant:complete",()=>{Oe&&(G.active||G.manuallyDeactivated||Oe==="assistant"&&!G.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!G.active&&!G.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{G.active=_.isVoiceActive(),ot("auto"),_.isVoiceActive()&&As()}):Va("auto"))},600))});ct.push(Uh);let qh=i.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ct.push(qh);let Yc=()=>{$t(!F,"user")},en=null,ln=null;if(I&&!W()){let{instance:l,element:m}=tc({config:r,plugins:o,onToggle:Yc});en=l,l||(ln=m)}en?e.appendChild(en.element):ln&&e.appendChild(ln),aa(),ys(),Uc(),ml(_.isStreaming()),Oc()||(Ft()==="follow"?yo(!0):Dc()),pl(),L&&(!I||W()?setTimeout(()=>gl(),0):F&&setTimeout(()=>gl(),200));let ia=()=>{var N,le,se,Z,we,Fe,_e,Ue,ze,mt,at,De,We,Ve,Qe,xt,B,Ne,He,Ze,It,$e;if(W()){Gn(),aa();return}let l=on(r),m=(le=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?le:!1,h=l||m||((Z=(se=r.launcher)==null?void 0:se.fullHeight)!=null?Z:!1),x=(we=e.ownerDocument.defaultView)!=null?we:window,S=(_e=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?_e:!0,H=(ze=(Ue=r.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?ze:640,q=x.innerWidth<=H,$=S&&q&&I;try{if($){po(),Ro(e,r);return}if(j&&(j=!1,po(),Ro(e,r)),!I&&!l){Q.style.height="",Q.style.width="";return}if(!m&&!l){let Jt=(at=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?at:r==null?void 0:r.launcherWidth,Ct=Jt!=null?Jt:zn;Q.style.width=Ct,Q.style.maxWidth=Ct}if(Uo(),!h){let Jt=x.innerHeight,Ct=64,cn=(We=(De=r.launcher)==null?void 0:De.heightOffset)!=null?We:0,Wn=Math.max(200,Jt-Ct),Dt=Math.min(640,Wn),gn=Math.max(200,Dt-cn);Q.style.height=`${gn}px`}}finally{if(Gn(),aa(),F&&I){let Ct=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((xt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),cn=(Ne=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?Ne:!1,Wn=(Ze=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?Ze:!0,Dt=on(r)&&Wn&&Ct,gn=cn||Wn&&Ct&&I||Dt;if(gn&&!an){let $n=e.getRootNode(),Je=$n instanceof ShadowRoot?$n.host:e.closest(".persona-host");Je&&!sn&&(sn=Jl(Je,($e=(It=r.launcher)==null?void 0:It.zIndex)!=null?$e:vn)),an=Xl(e.ownerDocument)}else gn||(sn==null||sn(),sn=null,an==null||an(),an=null)}}};ia();let Zc=(op=e.ownerDocument.defaultView)!=null?op:window;if(Zc.addEventListener("resize",ia),ct.push(()=>Zc.removeEventListener("resize",ia)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Gn()});l.observe(Be),ct.push(()=>l.disconnect())}An=Ce.scrollTop;let ed=Nr(Ce),zh=()=>{let l=Ce.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:Ce.ownerDocument.getSelection()},vl=()=>zg(zh(),Ce),td=()=>{let l=Ce.scrollTop,m=Nr(Ce),h=m<ed;if(ed=m,!tn()){An=l,_n();return}let{action:x,nextLastScrollTop:S}=ki({following:yn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:Wo(Ce,V),userScrollThreshold:w,isAutoScrolling:Sn||zo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=S,x==="resume"){vl()||ho();return}x==="pause"&&ea()};if(Ce.addEventListener("scroll",td,{passive:!0}),ct.push(()=>Ce.removeEventListener("scroll",td)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Mh()});l.observe(et),l.observe(Ce),ct.push(()=>l.disconnect())}let nd=()=>{tn()&&yn.isFollowing()&&vl()&&ea()},rd=Ce.ownerDocument;rd.addEventListener("selectionchange",nd),ct.push(()=>{rd.removeEventListener("selectionchange",nd)});let Vh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),od=l=>{ar()&&tn()&&yn.isFollowing()&&Vh.has(l.key)&&ea()},sd=l=>{if(!ar()||!tn()||!yn.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&ea()};Ce.addEventListener("keydown",od),Ce.addEventListener("focusin",sd),ct.push(()=>{Ce.removeEventListener("keydown",od),Ce.removeEventListener("focusin",sd)});let ad=l=>{if(!tn())return;let m=Li({following:yn.isFollowing(),deltaY:l.deltaY,nearBottom:Wo(Ce,V),resumeWhenNearBottom:!0});m==="pause"?ea():m==="resume"&&!vl()&&ho()};Ce.addEventListener("wheel",ad,{passive:!0}),ct.push(()=>Ce.removeEventListener("wheel",ad)),Vt.addEventListener("click",()=>{ta(),Ce.scrollTop=Ce.scrollHeight,An=Ce.scrollTop,ho(),yo(!0),_n()}),ct.push(()=>Vt.remove()),ct.push(()=>{Tn(),ta()});let id=()=>{qe&&(Lr&&(qe.removeEventListener("click",Lr),Lr=null),O()?(qe.style.display="",Lr=()=>{$t(!1,"user")},qe.addEventListener("click",Lr)):qe.style.display="none")};id(),(()=>{let{clearChatButton:l}=Ke;l&&l.addEventListener("click",()=>{_.clearMessages(),Pr.clear(),ho(),Eo(Ke.composerOverlay);try{localStorage.removeItem(Xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},P.syncFromMetadata(),K==null||K.clear(),Y==null||Y.reset(),ke==null||ke.update()})})(),At&&At.addEventListener("submit",Vc),xe==null||xe.addEventListener("keydown",Gc),xe==null||xe.addEventListener("input",Kc),xe==null||xe.addEventListener("paste",Xc);let ld=(sp=e.ownerDocument)!=null?sp:document;ld.addEventListener("keydown",Jc,!0);let cd="persona-attachment-drop-active",la=0,wl=()=>{la=0,Te.classList.remove(cd)},Ss=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&St!==null},dd=l=>{!nl(l.dataTransfer)||!Ss()||(la++,la===1&&Te.classList.add(cd))},pd=l=>{!nl(l.dataTransfer)||!Ss()||(la--,la<=0&&wl())},ud=l=>{!nl(l.dataTransfer)||!Ss()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},md=l=>{var h;if(!nl(l.dataTransfer)||!Ss())return;l.preventDefault(),l.stopPropagation(),wl();let m=Array.from((h=l.dataTransfer.files)!=null?h:[]);m.length!==0&&St.handleFiles(m)},xo=!0;Te.addEventListener("dragenter",dd,xo),Te.addEventListener("dragleave",pd,xo),e.addEventListener("dragover",ud,xo),e.addEventListener("drop",md,xo);let Ja=e.ownerDocument,gd=l=>{Ss()&&l.preventDefault()},fd=l=>{Ss()&&l.preventDefault()};Ja.addEventListener("dragover",gd),Ja.addEventListener("drop",fd),ct.push(()=>{At&&At.removeEventListener("submit",Vc),xe==null||xe.removeEventListener("keydown",Gc),xe==null||xe.removeEventListener("input",Kc),xe==null||xe.removeEventListener("paste",Xc),ld.removeEventListener("keydown",Jc,!0)}),ct.push(()=>{Te.removeEventListener("dragenter",dd,xo),Te.removeEventListener("dragleave",pd,xo),e.removeEventListener("dragover",ud,xo),e.removeEventListener("drop",md,xo),Ja.removeEventListener("dragover",gd),Ja.removeEventListener("drop",fd),wl()}),ct.push(()=>{_.cancel()}),en?ct.push(()=>{en==null||en.destroy()}):ln&&ct.push(()=>{ln==null||ln.remove()});let nn={update(l){var Un,Hr,un,mn,nr,Co,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu,qu,zu,Vu,Ku,Gu,Ju,Xu,Qu,Yu,Zu,em,tm,nm,rm,om,sm,am,im,lm,cm,dm,pm,um,mm,gm,fm,hm,ym,bm;let m=r.toolCall,h=r.messageActions,x=(Un=r.layout)==null?void 0:Un.messages,S=r.colorScheme,H=r.loadingIndicator,q=r.iterationDisplay,$=(Hr=r.features)==null?void 0:Hr.showReasoning,N=(un=r.features)==null?void 0:un.showToolCalls,le=(mn=r.features)==null?void 0:mn.toolCallDisplay,se=(nr=r.features)==null?void 0:nr.reasoningDisplay,Z=(up=(Co=r.features)==null?void 0:Co.streamAnimation)==null?void 0:up.type;r={...r,...l},po(),Ro(e,r),Ki(e,r),Gi(e,r),Mr(),r.colorScheme!==S&&Zs();let we=Fa.getForInstance(r.plugins);o.length=0,o.push(...we),I=(gp=(mp=r.launcher)==null?void 0:mp.enabled)!=null?gp:!0,M=(hp=(fp=r.launcher)==null?void 0:fp.autoExpand)!=null?hp:!1,Pe=(bp=(yp=r.features)==null?void 0:yp.showReasoning)!=null?bp:!0,Ie=(vp=(xp=r.features)==null?void 0:xp.showToolCalls)!=null?vp:!0,Se=(Cp=(wp=r.features)==null?void 0:wp.scrollToBottom)!=null?Cp:{};let Fe=Ft();oe=(Sp=(Ap=r.features)==null?void 0:Ap.scrollBehavior)!=null?Sp:{},Fe!==Ft()&&(ta(),ho()),oo(),_n();let _e=re;if(re=(Ep=(Tp=r.features)==null?void 0:Tp.showEventStreamToggle)!=null?Ep:!1,re&&!_e){if(K||(ye=new Na(ie),K=new Da(je,ye),Y=Y!=null?Y:new Oa,ye.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),_.setSSEEventCallback((ne,Et)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,ne,Et),Y==null||Y.processEvent(ne,Et),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!bt&&Le){let ne=(kp=(Mp=r.features)==null?void 0:Mp.eventStream)==null?void 0:kp.classNames,Et="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=y("button",Et),bt.style.width="28px",bt.style.height="28px",bt.style.color=kn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let qt=he("activity","18px","currentColor",1.5);qt&&bt.appendChild(qt);let it=Ke.clearChatButtonWrapper,Lt=Ke.closeButtonWrapper,dn=it||Lt;dn&&dn.parentNode===Le?Le.insertBefore(bt,dn):Le.appendChild(bt),bt.addEventListener("click",()=>{X?dr():$r()})}}else!re&&_e&&(dr(),bt&&(bt.remove(),bt=null),K==null||K.clear(),ye==null||ye.destroy(),K=null,ye=null,Y==null||Y.reset(),Y=null);if(((Lp=r.launcher)==null?void 0:Lp.enabled)===!1&&en&&(en.destroy(),en=null),((Pp=r.launcher)==null?void 0:Pp.enabled)===!1&&ln&&(ln.remove(),ln=null),((Ip=r.launcher)==null?void 0:Ip.enabled)!==!1&&!en&&!ln){let{instance:ne,element:Et}=tc({config:r,plugins:o,onToggle:Yc});en=ne,ne||(ln=Et),e.appendChild(Et)}en&&en.update(r),me&&((Rp=r.launcher)==null?void 0:Rp.title)!==void 0&&(me.textContent=r.launcher.title),Ee&&((Wp=r.launcher)==null?void 0:Wp.subtitle)!==void 0&&(Ee.textContent=r.launcher.subtitle);let Ue=(Hp=r.layout)==null?void 0:Hp.header;if((Ue==null?void 0:Ue.layout)!==U&&Le){let ne=Ue?Us(r,Ue,{showClose:O(),onClose:()=>$t(!1,"user")}):Zr({config:r,showClose:O(),onClose:()=>$t(!1,"user")});nt.replaceHeader(ne),Le=nt.header.element,k=nt.header.iconHolder,me=nt.header.headerTitle,Ee=nt.header.headerSubtitle,qe=nt.header.closeButton,U=Ue==null?void 0:Ue.layout}else if(Ue&&(k&&(k.style.display=Ue.showIcon===!1?"none":""),me&&(me.style.display=Ue.showTitle===!1?"none":""),Ee&&(Ee.style.display=Ue.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ue.showCloseButton===!1?"none":""),Ke.clearChatButtonWrapper)){let ne=Ue.showClearChat;if(ne!==void 0){Ke.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Et}=Ke;Et&&!Et.classList.contains("persona-absolute")&&(ne?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let mt=((Bp=r.layout)==null?void 0:Bp.showHeader)!==!1;Le&&(Le.style.display=mt?"":"none");let at=((Dp=r.layout)==null?void 0:Dp.showFooter)!==!1;Be&&(Be.style.display=at?"":"none"),Gn(),_n(),I!==R?I?$t(M,"auto"):(F=!0,aa()):M!==C&&$t(M,"auto"),C=M,R=I,ia(),id();let Ve=JSON.stringify(l.toolCall)!==JSON.stringify(m),Qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),xt=JSON.stringify((Np=r.layout)==null?void 0:Np.messages)!==JSON.stringify(x),B=((Op=r.loadingIndicator)==null?void 0:Op.render)!==(H==null?void 0:H.render)||((Fp=r.loadingIndicator)==null?void 0:Fp.renderIdle)!==(H==null?void 0:H.renderIdle)||((_p=r.loadingIndicator)==null?void 0:_p.showBubble)!==(H==null?void 0:H.showBubble),Ne=r.iterationDisplay!==q,He=((jp=($p=r.features)==null?void 0:$p.showReasoning)!=null?jp:!0)!==($!=null?$:!0)||((qp=(Up=r.features)==null?void 0:Up.showToolCalls)!=null?qp:!0)!==(N!=null?N:!0)||JSON.stringify((zp=r.features)==null?void 0:zp.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify((Vp=r.features)==null?void 0:Vp.reasoningDisplay)!==JSON.stringify(se);(Ve||Qe||xt||B||Ne||He)&&_&&(bs++,na(et,_.getMessages(),te));let It=(Gp=(Kp=r.features)==null?void 0:Kp.streamAnimation)==null?void 0:Gp.type;if(It!==Z&&It&&It!=="none"){let ne=js(It,(Xp=(Jp=r.features)==null?void 0:Jp.streamAnimation)==null?void 0:Xp.plugins);ne&&Wi(ne,e)}let $e=(Qp=r.launcher)!=null?Qp:{},Jt=(Yp=$e.headerIconHidden)!=null?Yp:!1,Ct=(eu=(Zp=r.layout)==null?void 0:Zp.header)==null?void 0:eu.showIcon,cn=Jt||Ct===!1,Wn=$e.headerIconName,Dt=(tu=$e.headerIconSize)!=null?tu:"48px";if(k){let ne=Te.querySelector(".persona-border-b-persona-divider"),Et=ne==null?void 0:ne.querySelector(".persona-flex-col");if(cn)k.style.display="none",ne&&Et&&!ne.contains(Et)&&ne.insertBefore(Et,ne.firstChild);else{if(k.style.display="",k.style.height=Dt,k.style.width=Dt,ne&&Et&&(ne.contains(k)?k.nextSibling!==Et&&(k.remove(),ne.insertBefore(k,Et)):ne.insertBefore(k,Et)),Wn){let it=parseFloat(Dt)||24,Lt=he(Wn,it*.6,"currentColor",1);Lt?k.replaceChildren(Lt):k.textContent=(nu=$e.agentIconText)!=null?nu:"\u{1F4AC}"}else if($e.iconUrl){let it=k.querySelector("img");if(it)it.src=$e.iconUrl,it.style.height=Dt,it.style.width=Dt;else{let Lt=document.createElement("img");Lt.src=$e.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Dt,Lt.style.width=Dt,k.replaceChildren(Lt)}}else{let it=k.querySelector("svg"),Lt=k.querySelector("img");(it||Lt)&&k.replaceChildren(),k.textContent=(ru=$e.agentIconText)!=null?ru:"\u{1F4AC}"}let qt=k.querySelector("img");qt&&(qt.style.height=Dt,qt.style.width=Dt)}}let gn=(su=(ou=r.layout)==null?void 0:ou.header)==null?void 0:su.showTitle,$n=(iu=(au=r.layout)==null?void 0:au.header)==null?void 0:iu.showSubtitle;if(me&&(me.style.display=gn===!1?"none":""),Ee&&(Ee.style.display=$n===!1?"none":""),qe){((cu=(lu=r.layout)==null?void 0:lu.header)==null?void 0:cu.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let Et=(du=$e.closeButtonSize)!=null?du:"32px",qt=(pu=$e.closeButtonPlacement)!=null?pu:"inline";qe.style.height=Et,qe.style.width=Et;let{closeButtonWrapper:it}=Ke,Lt=qt==="top-right",dn=it==null?void 0:it.classList.contains("persona-absolute");if(it&&Lt!==dn)if(it.remove(),Lt)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Te.style.position="relative",Te.appendChild(it);else{let pt=(mu=(uu=$e.clearChat)==null?void 0:uu.placement)!=null?mu:"inline",pn=(fu=(gu=$e.clearChat)==null?void 0:gu.enabled)!=null?fu:!0;it.className=pn&&pt==="inline"?"":"persona-ml-auto";let Hn=Te.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(it)}if(qe.style.color=$e.closeButtonColor||kn.actionIconColor,$e.closeButtonBackgroundColor?(qe.style.backgroundColor=$e.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),$e.closeButtonBorderWidth||$e.closeButtonBorderColor){let pt=$e.closeButtonBorderWidth||"0px",pn=$e.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${pn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");$e.closeButtonBorderRadius?(qe.style.borderRadius=$e.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),$e.closeButtonPaddingX?(qe.style.paddingLeft=$e.closeButtonPaddingX,qe.style.paddingRight=$e.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),$e.closeButtonPaddingY?(qe.style.paddingTop=$e.closeButtonPaddingY,qe.style.paddingBottom=$e.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let xn=(hu=$e.closeButtonIconName)!=null?hu:"x",fr=(yu=$e.closeButtonIconText)!=null?yu:"\xD7";qe.innerHTML="";let Mn=he(xn,"28px","currentColor",1);Mn?qe.appendChild(Mn):qe.textContent=fr;let Zt=(bu=$e.closeButtonTooltipText)!=null?bu:"Close chat",qn=(xu=$e.closeButtonShowTooltip)!=null?xu:!0;if(qe.setAttribute("aria-label",Zt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),qn&&Zt)){let pt=null,pn=()=>{if(pt||!qe)return;let es=qe.ownerDocument,ca=es.body;if(!ca)return;pt=Dr(es,"div","persona-clear-chat-tooltip"),pt.textContent=Zt;let da=Dr(es,"div");da.className="persona-clear-chat-tooltip-arrow",pt.appendChild(da);let ts=qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Ho),pt.style.left=`${ts.left+ts.width/2}px`,pt.style.top=`${ts.top-8}px`,pt.style.transform="translate(-50%, -100%)",ca.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",pn),it.addEventListener("mouseleave",Hn),qe.addEventListener("focus",pn),qe.addEventListener("blur",Hn),it._cleanupTooltip=()=>{Hn(),it&&(it.removeEventListener("mouseenter",pn),it.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",pn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Rt}=Ke;if(Je){let ne=(vu=$e.clearChat)!=null?vu:{},Et=(wu=ne.enabled)!=null?wu:!0,qt=(Au=(Cu=r.layout)==null?void 0:Cu.header)==null?void 0:Au.showClearChat,it=qt!==void 0?qt:Et,Lt=(Su=ne.placement)!=null?Su:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:dn}=Ke;!W()&&dn&&!dn.classList.contains("persona-absolute")&&(it?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let xn=Lt==="top-right",fr=Rt.classList.contains("persona-absolute");if(!W()&&xn!==fr&&it){if(Rt.remove(),xn)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",Te.style.position="relative",Te.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let Zt=Te.querySelector(".persona-border-b-persona-divider"),qn=Ke.closeButtonWrapper;Zt&&qn&&qn.parentElement===Zt?Zt.insertBefore(Rt,qn):Zt&&Zt.appendChild(Rt)}let Mn=Ke.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(xn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(it){if(!W()){let pt=(Tu=ne.size)!=null?Tu:"32px";Je.style.height=pt,Je.style.width=pt}let dn=(Eu=ne.iconName)!=null?Eu:"refresh-cw",xn=(Mu=ne.iconColor)!=null?Mu:"";Je.style.color=xn||kn.actionIconColor,Je.innerHTML="";let fr=W()?"14px":"20px",Mn=he(dn,fr,"currentColor",2);if(Mn&&Je.appendChild(Mn),ne.backgroundColor?(Je.style.backgroundColor=ne.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let pt=ne.borderWidth||"0px",pn=ne.borderColor||"transparent";Je.style.border=`${pt} solid ${pn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");ne.borderRadius?(Je.style.borderRadius=ne.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),ne.paddingX?(Je.style.paddingLeft=ne.paddingX,Je.style.paddingRight=ne.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),ne.paddingY?(Je.style.paddingTop=ne.paddingY,Je.style.paddingBottom=ne.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Zt=(ku=ne.tooltipText)!=null?ku:"Clear chat",qn=(Lu=ne.showTooltip)!=null?Lu:!0;if(Je.setAttribute("aria-label",Zt),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),qn&&Zt)){let pt=null,pn=()=>{if(pt||!Je)return;let es=Je.ownerDocument,ca=es.body;if(!ca)return;pt=Dr(es,"div","persona-clear-chat-tooltip"),pt.textContent=Zt;let da=Dr(es,"div");da.className="persona-clear-chat-tooltip-arrow",pt.appendChild(da);let ts=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Ho),pt.style.left=`${ts.left+ts.width/2}px`,pt.style.top=`${ts.top-8}px`,pt.style.transform="translate(-50%, -100%)",ca.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};Rt.addEventListener("mouseenter",pn),Rt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",pn),Je.addEventListener("blur",Hn),Rt._cleanupTooltip=()=>{Hn(),Rt&&(Rt.removeEventListener("mouseenter",pn),Rt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",pn),Je.removeEventListener("blur",Hn))}}}}let jn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[_a],Go=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[gs.message,gs.messageAndClick];P=$a({parsers:jn,handlers:Go,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),te=Ff(r,P,pe),_.updateConfig(r),na(et,_.getMessages(),te),ys(),Uc(),ml(_.isStreaming());let Jo=((Pu=r.voiceRecognition)==null?void 0:Pu.enabled)===!0,Xo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Qo=((Ru=(Iu=r.voiceRecognition)==null?void 0:Iu.provider)==null?void 0:Ru.type)==="runtype";if(Jo&&(Xo||Qo))if(!D||!ve){let ne=_h(r.voiceRecognition,r.sendButton);ne&&(D=ne.micButton,ve=ne.micButtonWrapper,yt.insertBefore(ve,wn),D.addEventListener("click",Ga),D.disabled=_.isStreaming())}else{let ne=(Wu=r.voiceRecognition)!=null?Wu:{},Et=(Hu=r.sendButton)!=null?Hu:{},qt=(Bu=ne.iconName)!=null?Bu:"mic",it=(Du=Et.size)!=null?Du:"40px",Lt=(Nu=ne.iconSize)!=null?Nu:it,dn=parseFloat(Lt)||24;D.style.width=Lt,D.style.height=Lt,D.style.minWidth=Lt,D.style.minHeight=Lt;let xn=(Fu=(Ou=ne.iconColor)!=null?Ou:Et.textColor)!=null?Fu:"currentColor";D.innerHTML="";let fr=he(qt,dn,xn,2);fr?D.appendChild(fr):D.textContent="\u{1F3A4}";let Mn=(_u=ne.backgroundColor)!=null?_u:Et.backgroundColor;Mn?D.style.backgroundColor=Mn:D.style.backgroundColor="",xn?D.style.color=xn:D.style.color="var(--persona-text, #111827)",ne.borderWidth?(D.style.borderWidth=ne.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ne.borderColor?D.style.borderColor=ne.borderColor:D.style.borderColor="",ne.paddingX?(D.style.paddingLeft=ne.paddingX,D.style.paddingRight=ne.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ne.paddingY?(D.style.paddingTop=ne.paddingY,D.style.paddingBottom=ne.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Zt=ve==null?void 0:ve.querySelector(".persona-send-button-tooltip"),qn=($u=ne.tooltipText)!=null?$u:"Start voice recognition";if(((ju=ne.showTooltip)!=null?ju:!1)&&qn)if(Zt)Zt.textContent=qn,Zt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=qn,ve==null||ve.insertBefore(pn,D)}else Zt&&(Zt.style.display="none");ve.style.display="",D.disabled=_.isStreaming()}else D&&ve&&(ve.style.display="none",((qu=(Uu=r.voiceRecognition)==null?void 0:Uu.provider)==null?void 0:qu.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Wr&&bo());if(((zu=r.attachments)==null?void 0:zu.enabled)===!0)if(!ht||!de){let ne=(Vu=r.attachments)!=null?Vu:{},qt=(Gu=((Ku=r.sendButton)!=null?Ku:{}).size)!=null?Gu:"40px";Pt||(Pt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pt.style.display="none",At.insertBefore(Pt,xe)),Xe||(Xe=document.createElement("input"),Xe.type="file",Xe.accept=((Ju=ne.allowedTypes)!=null?Ju:Yr).join(","),Xe.multiple=((Xu=ne.maxFiles)!=null?Xu:4)>1,Xe.style.display="none",Xe.setAttribute("aria-label","Attach files"),At.insertBefore(Xe,xe)),ht=y("div","persona-send-button-wrapper"),de=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),de.type="button",de.setAttribute("aria-label",(Qu=ne.buttonTooltipText)!=null?Qu:"Attach file");let it=(Yu=ne.buttonIconName)!=null?Yu:"paperclip",Lt=qt,dn=parseFloat(Lt)||40,xn=Math.round(dn*.6);de.style.width=Lt,de.style.height=Lt,de.style.minWidth=Lt,de.style.minHeight=Lt,de.style.fontSize="18px",de.style.lineHeight="1",de.style.backgroundColor="transparent",de.style.color="var(--persona-primary, #111827)",de.style.border="none",de.style.borderRadius="6px",de.style.transition="background-color 0.15s ease",de.addEventListener("mouseenter",()=>{de.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),de.addEventListener("mouseleave",()=>{de.style.backgroundColor="transparent"});let fr=he(it,xn,"currentColor",1.5);fr?de.appendChild(fr):de.textContent="\u{1F4CE}",de.addEventListener("click",qn=>{qn.preventDefault(),Xe==null||Xe.click()}),ht.appendChild(de);let Mn=(Zu=ne.buttonTooltipText)!=null?Zu:"Attach file",Zt=y("div","persona-send-button-tooltip");Zt.textContent=Mn,ht.appendChild(Zt),Ye.append(ht),!St&&Xe&&Pt&&(St=ls.fromConfig(ne),St.setPreviewsContainer(Pt),Xe.addEventListener("change",async()=>{St&&(Xe!=null&&Xe.files)&&(await St.handleFileSelect(Xe.files),Xe.value="")})),Te.querySelector(".persona-attachment-drop-overlay")||Te.appendChild(_f(ne.dropOverlay))}else{ht.style.display="";let ne=(em=r.attachments)!=null?em:{};Xe&&(Xe.accept=((tm=ne.allowedTypes)!=null?tm:Yr).join(","),Xe.multiple=((nm=ne.maxFiles)!=null?nm:4)>1),St&&St.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else ht&&(ht.style.display="none"),St&&St.clearAttachments(),(rm=Te.querySelector(".persona-attachment-drop-overlay"))==null||rm.remove();let Xt=(om=r.sendButton)!=null?om:{},Yo=(sm=Xt.useIcon)!=null?sm:!1,vo=(am=Xt.iconText)!=null?am:"\u2191",wo=Xt.iconName,Gr=(im=Xt.tooltipText)!=null?im:"Send message",Zo=(lm=Xt.showTooltip)!=null?lm:!1,tt=(cm=Xt.size)!=null?cm:"40px",Ot=Xt.backgroundColor,Nt=Xt.textColor;if(Yo){if(ue.style.width=tt,ue.style.height=tt,ue.style.minWidth=tt,ue.style.minHeight=tt,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.innerHTML="",Nt?ue.style.color=Nt:ue.style.color="var(--persona-button-primary-fg, #ffffff)",wo){let ne=parseFloat(tt)||24,Et=(Nt==null?void 0:Nt.trim())||"currentColor",qt=he(wo,ne,Et,2);qt?ue.appendChild(qt):ue.textContent=vo}else ue.textContent=vo;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ot?(ue.style.backgroundColor=Ot,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=(pm=(dm=r.copy)==null?void 0:dm.sendButtonLabel)!=null?pm:"Send",ue.style.width="",ue.style.height="",ue.style.minWidth="",ue.style.minHeight="",ue.style.fontSize="",ue.style.lineHeight="",ue.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ot?(ue.style.backgroundColor=Ot,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),Nt?ue.style.color=Nt:ue.classList.add("persona-text-white");Xt.borderWidth?(ue.style.borderWidth=Xt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Xt.borderColor?ue.style.borderColor=Xt.borderColor:ue.style.borderColor="",Xt.paddingX?(ue.style.paddingLeft=Xt.paddingX,ue.style.paddingRight=Xt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Xt.paddingY?(ue.style.paddingTop=Xt.paddingY,ue.style.paddingBottom=Xt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Kt=wn==null?void 0:wn.querySelector(".persona-send-button-tooltip");if(Zo&&Gr)if(Kt)Kt.textContent=Gr,Kt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Gr,wn==null||wn.insertBefore(ne,ue)}else Kt&&(Kt.style.display="none");let jt=(hm=(um=r.layout)==null?void 0:um.contentMaxWidth)!=null?hm:W()?(fm=(gm=(mm=r.launcher)==null?void 0:mm.composerBar)==null?void 0:gm.contentMaxWidth)!=null?fm:"720px":void 0;jt?(et.style.maxWidth=jt,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%",At&&(At.style.maxWidth=jt,At.style.marginLeft="auto",At.style.marginRight="auto"),zt&&(zt.style.maxWidth=jt,zt.style.marginLeft="auto",zt.style.marginRight="auto")):(et.style.maxWidth="",et.style.marginLeft="",et.style.marginRight="",et.style.width="",At&&(At.style.maxWidth="",At.style.marginLeft="",At.style.marginRight=""),zt&&(zt.style.maxWidth="",zt.style.marginLeft="",zt.style.marginRight=""));let gt=(ym=r.statusIndicator)!=null?ym:{},Ut=(bm=gt.visible)!=null?bm:!0;if(hn.style.display=Ut?"":"none",_){let ne=_.getStatus();Ht(hn,(qt=>{var it,Lt,dn,xn;return qt==="idle"?(it=gt.idleText)!=null?it:rn.idle:qt==="connecting"?(Lt=gt.connectingText)!=null?Lt:rn.connecting:qt==="connected"?(dn=gt.connectedText)!=null?dn:rn.connected:qt==="error"?(xn=gt.errorText)!=null?xn:rn.error:rn[qt]})(ne),gt,ne)}hn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";hn.classList.add(fn)},open(){O()&&$t(!0,"api")},close(){O()&&$t(!1,"api")},toggle(){O()&&$t(!F,"api")},reconnect(){_.reconnectNow()},clearChat(){Cn=!1,_.clearMessages(),Pr.clear(),ho();try{localStorage.removeItem(Xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let m=c.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},P.syncFromMetadata(),K==null||K.clear(),Y==null||Y.reset(),ke==null||ke.update()},setMessage(l){return!xe||_.isStreaming()?!1:(!F&&O()&&$t(!0,"system"),xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let m=(l==null?void 0:l.trim())||xe.value.trim();return m?(!F&&O()&&$t(!0,"system"),xe.value="",xe.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return _.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!F&&O()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),_.toggleVoice().then(()=>{G.active=_.isVoiceActive(),ot("user"),_.isVoiceActive()&&As()})),!0):Wr?!0:Qc()?(!F&&O()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),Va("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),ot("user"),Kr()}),!0):!1:Wr?(G.manuallyDeactivated=!0,dt(),bo("user"),!0):!1},injectMessage(l){return!F&&O()&&$t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!F&&O()&&$t(!0,"system");let m=_.injectAssistantMessage(l);return ee&&(ee=!1,Me&&(clearTimeout(Me),Me=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(l){return!F&&O()&&$t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!F&&O()&&$t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!F&&O()&&$t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!F&&O()&&$t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!F&&O()&&$t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,m){return _.connectStream(l,m)},__pushEventStreamEvent(l){K&&(Y==null||Y.processEvent(l.type,l.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!re||!K||$r()},hideEventStream(){X&&dr()},isEventStreamVisible(){return X},showArtifacts(){sr(r)&&(Cn=!1,Mr(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){sr(r)&&(Cn=!0,Mr())},upsertArtifact(l){return sr(r)?(Cn=!1,_.upsertArtifact(l)):null},selectArtifact(l){sr(r)&&_.selectArtifact(l)},clearArtifacts(){sr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return I&&!F&&!W()||!xe?!1:(xe.focus(),!0)},async resolveApproval(l,m,h){let S=_.getMessages().find(H=>{var q;return H.variant==="approval"&&((q=H.approval)==null?void 0:q.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){_.resolveWebMcpApproval(S.id,m);return}return _.resolveApproval(S.approval,m,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){v(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return O()&&F},isVoiceActive(){return G.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:O()&&F,launcherEnabled:I,voiceActive:G.active,streaming:_.isStreaming()}},showCSATFeedback(l){!F&&O()&&$t(!0,"system");let m=et.querySelector(".persona-feedback-container");m&&m.remove();let h=el({onSubmit:async(x,S)=>{var H;_.isClientTokenMode()&&await _.submitCSATFeedback(x,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,x,S)},onDismiss:l==null?void 0:l.onDismiss,...l});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!F&&O()&&$t(!0,"system");let m=et.querySelector(".persona-feedback-container");m&&m.remove();let h=tl({onSubmit:async(x,S)=>{var H;_.isClientTokenMode()&&await _.submitNPSFeedback(x,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,x,S)},onDismiss:l==null?void 0:l.onDismiss,...l});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return _.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return _.submitNPSFeedback(l,m)},destroy(){Ko!=null&&(clearInterval(Ko),Ko=null),ct.forEach(l=>l()),fe.remove(),lt==null||lt.remove(),en==null||en.destroy(),ln==null||ln.remove(),Lr&&qe.removeEventListener("click",Lr)}};if((((ap=n==null?void 0:n.debugTools)!=null?ap:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:nn,getMessages:nn.getMessages,getStatus:nn.getStatus,getMetadata:nn.getPersistentMetadata,updateMetadata:nn.updatePersistentMetadata,clearHistory:()=>nn.clearChat(),setVoiceActive:h=>h?nn.startVoiceRecognition():nn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ct.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",m),ct.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let $=le=>{let se=le.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&nn.showEventStream()},N=le=>{let se=le.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",N),ct.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",N)})}let h=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&nn.showArtifacts()},x=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&nn.hideArtifacts()},S=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&nn.upsertArtifact(N.artifact)},H=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&nn.selectArtifact(N.id)},q=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",q),ct.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",q)})}let tr=$x(r.persistState);if(tr&&O()){let l=jx(tr.storage),m=`${tr.keyPrefix}widget-open`,h=`${tr.keyPrefix}widget-voice`,x=`${tr.keyPrefix}widget-voice-mode`;if(l){let S=((ip=tr.persist)==null?void 0:ip.openState)&&l.getItem(m)==="true",H=((lp=tr.persist)==null?void 0:lp.voiceState)&&l.getItem(h)==="true",q=((cp=tr.persist)==null?void 0:cp.voiceState)&&l.getItem(x)==="true";if(S&&setTimeout(()=>{nn.open(),setTimeout(()=>{var $;if(H||q)nn.startVoiceRecognition();else if(($=tr.persist)!=null&&$.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(dp=tr.persist)!=null&&dp.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(pp=tr.persist)!=null&&pp.voiceState&&(i.on("voice:state",$=>{l.setItem(h,$.active?"true":"false")}),i.on("user:message",$=>{l.setItem(x,$.viaVoice?"true":"false")})),tr.clearOnChatClear){let $=()=>{l.removeItem(m),l.removeItem(h),l.removeItem(x)},N=()=>$();window.addEventListener("persona:clear-chat",N),ct.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return f&&O()&&setTimeout(()=>{nn.open()},0),ws(),qa||Em().then(()=>{_&&(bs++,Pr.clear(),na(et,_.getMessages(),te))}).catch(()=>{}),nn};var Ux=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},qx=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},zx=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Vx=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||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.")},$f=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},vc=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=""},jf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",vc(e)},yc=e=>{e.style.transition=""},bc=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=""},xc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ol=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Kx=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Gx=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Uf=(e,t,n,r,o,s,a)=>{var b,v,T,E,P,I;let i=Vn(s),d=i.reveal==="push";Kx(e,t,n,r,d),Gx(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(b=s==null?void 0:s.launcher)==null?void 0:b.mobileFullscreen)!=null?v:!0,u=(E=(T=s==null?void 0:s.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),bc(t),yc(r),jf(r),xc(n),ol(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((I=(P=s==null?void 0:s.launcher)==null?void 0:P.zIndex)!=null?I:vn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),jf(r),qx(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",bc(t),yc(r),xc(n),ol(o,r);let M=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=M,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",yc(r),vc(r),ol(o,r);let M=Ux(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",R=i.side==="right"?a?-M:0:a?0:-M;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=`${L+M}px`,t.style.transition=C,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${L}px`,n.style.maxWidth=`${L}px`,n.style.minWidth=`${L}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",bc(t),vc(r),xc(n),ol(o,r);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",zx(r,i.maxHeight),r.style.overflow=M||R?"hidden":"visible",r.style.transition=C,M&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Jx=(e,t)=>{let n=e.ownerDocument.createElement("div");return $f(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){$f(n,r)},destroy(){n.remove()}}},Xx=(e,t)=>{var I,M,L,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="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"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),u=(M=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||M?(C=(L=t==null?void 0:t.launcher)==null?void 0:L.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},b=()=>{g(),Vn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Uf(a,i,d,c,p,t,u)}),f.observe(a))},v=!1,T=()=>{Uf(a,i,d,c,p,t,u),b(),u&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Vx(a,Vn(t)))},E=a.ownerDocument.defaultView,P=()=>{T()};return E==null||E.addEventListener("resize",P),Vn(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),T(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let U=R.launcherEnabled?R.open:!0;u!==U&&(u=U,T())},updateConfig(R){var U,j;t=R,((j=(U=t==null?void 0:t.launcher)==null?void 0:U.enabled)!=null?j:!0)===!1&&(u=!0),T()},destroy(){E==null||E.removeEventListener("resize",P),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},ja=(e,t)=>on(t)?Xx(e,t):Jx(e,t);var wc={},Qx=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Yx=()=>{try{if(typeof wc!="undefined"&&wc.url)return new URL("../widget.css",wc.url).href}catch{}return null},qf=(e,t)=>{let n=Yx(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Cc=e=>{var T;let t=Qx(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=ja(t,o),a,i=[],d=(E,P)=>{var C,R;let M=!((R=(C=P==null?void 0:P.launcher)==null?void 0:C.enabled)!=null?R:!0)||on(P),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),M&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),n){let U=E.attachShadow({mode:"open"});U.appendChild(L),qf(U,r)}else E.appendChild(L),qf(E,r);return t.id&&L.setAttribute("data-persona-instance",t.id),L},c=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let E=d(s.host,o);a=rl(E,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),(T=e.onChatReady)==null||T.call(e);let g=E=>{f(),s.destroy(),s=ja(t,E),o=E,u()},b={update(E){var R,U,j,W,O,F;let P={...o,...E,launcher:{...(R=o==null?void 0:o.launcher)!=null?R:{},...(U=E==null?void 0:E.launcher)!=null?U:{},dock:{...(W=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?W:{},...(F=(O=E==null?void 0:E.launcher)==null?void 0:O.dock)!=null?F:{}}}},I=on(o),M=on(P),L=Do(o),C=Do(P);if(I!==M||L!==C){g(P);return}o=P,s.updateConfig(o),a.update(E),c()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(b,{get(E,P,I){if(P==="host")return s.host;if(P in E)return Reflect.get(E,P,I);let M=a[P];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Jf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Zx=new Set(["button","a","input","select","textarea","details","summary"]),ev=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ac=/\b(product|card|item|listing|result)\b/i,Tc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,tv=3e3,nv=100;function Xf(e){let t=typeof e.className=="string"?e.className:"";if(Ac.test(t)||e.id&&Ac.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ac.test(r.value))return!0}return!1}function Qf(e){var t;return Tc.test(((t=e.textContent)!=null?t:"").trim())}function Yf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function rv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function zf(e){let t=e.match(Tc);return t?t[0]:null}function Vf(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function ov(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var sv="commerce-card",av="result-card";function Kf(e){return!Xf(e)||!Qf(e)||!Yf(e)&&!rv(e)?0:5200}function Gf(e){var r;return!Xf(e)||Qf(e)||!Yf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ec=[{id:sv,scoreElement(e){return Kf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Tc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(Kf(e)===0)return null;let{title:n,href:r}=Vf(e),o=(p=(c=zf(((d=e.textContent)!=null?d:"").trim()))!=null?c:zf(t.text))!=null?p:"",s=ov(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
- `)}},{id:av,scoreElement(e){return Gf(e)},formatSummary(e,t){if(Gf(e)===0)return null;let{title:n,href:r}=Vf(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
- `)}}];function iv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function lv(e){var p,u,f,g,b,v,T,E,P,I,M,L,C;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(b=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?b:".persona-host",o=(T=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?T:200,s=(P=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?P:!0,a=(I=t.root)!=null?I:e.root,i=(M=t.mode)!=null?M:"structured",d=(L=t.maxCandidates)!=null?L:Math.max(500,n*10),c=(C=e.rules)!=null?C:Ec;return i==="simple"&&e.rules&&e.rules.length>0?(iv(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function Sc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var cv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function dv(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"||Zx.has(t)||n&&ev.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Zf(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 pv(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);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 d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Mc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Sc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of cv){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Sc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>Sc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function uv(e){return e==="static"?nv:tv}function eh(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:Mc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:dv(e),attributes:pv(e)}}function mv(e,t,n,r){let o=uv(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function gv(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function fv(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(Jf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Zf(c)){i=a.nextNode();continue}let u=eh(c,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(T=>T==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:b,formattingRule:v}=mv(c,u,e.rules,n);o.push({el:c,domIndex:s,enriched:u,score:b,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;gv(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function hv(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(Jf.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Zf(d)){s=o.nextNode();continue}let p=eh(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function th(e={}){var r;let t=lv(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?hv(t,n):fv(t,n):[]}var sl=100;function nh(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
111
+ `}if(!x&&!l){let Ot="max-height: -moz-available !important; max-height: stretch !important;",Nt=m?"":"padding-top: 1.25em !important;",Kt=m?"":`z-index: ${(tt=(ts=r.launcher)==null?void 0:ts.zIndex)!=null?tt:Cn} !important;`;fe.style.cssText+=Ot+Nt+Kt}Qe()};go(),Ho(e,r),Yi(e,r),Zi(e,r);let ct=[];ct.push(()=>{document.removeEventListener("keydown",Ur)}),ct.push(()=>{cr!==null&&clearTimeout(cr)});let on=null,sn=null;ct.push(()=>{on==null||on(),on=null,sn==null||sn(),sn=null}),Nn&&ct.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),ct.push(()=>{Yn==null||Yn(),Yn=null,bs(),_t&&(_t.remove(),_t=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),re&&ct.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),ke==null||ke.destroy(),ke=null,K==null||K.destroy(),K=null,ye=null});let Mr=null,ra=()=>{Mr&&(Mr(),Mr=null),r.colorScheme==="auto"&&(Mr=Li(()=>{Ho(e,r)}))};ra(),ct.push(()=>{Mr&&(Mr(),Mr=null)}),ct.push(a);let zr=(pp=r.features)==null?void 0:pp.streamAnimation;if(zr!=null&&zr.type&&zr.type!=="none"){let l=Vs(zr.type,zr.plugins);l&&(Oi(l,e),ct.push(()=>uf(e)))}let Vo=If(zt),kr=null,$,xs=l=>{var x,C;if(!$)return;let m=l!=null?l:$.getMessages(),h=((C=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:C.enabled)!==!1?ci(m):null;h?Vo.render(h,$,xe,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(k=>k.role==="user")?Vo.render([],$,xe,m):Vo.render(r.suggestionChips,$,xe,m,r.suggestionChipsConfig)},Zn=!1,Lr=Zg(),Vr=new Map,Pr=new Map,pr=new Map,vs=0,Ga=os()!==null,xn=Ri(),Tn=0,ur=null,En=!1,Ko=!1,mr=0,vn=null,Ir=null,ws=!1,Go=!1,Cs=null,fo=!0,ho=!1,st=null,w=4,V=24,z=80,J=new Map,G={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Oe=(mp=(up=r.voiceRecognition)==null?void 0:up.autoResume)!=null?mp:!1,ot=l=>{i.emit("voice:state",{active:G.active,source:l,timestamp:Date.now()})},dt=()=>{v(l=>({...l,voiceState:{active:G.active,timestamp:Date.now(),manuallyDeactivated:G.manuallyDeactivated}}))},fl=()=>{var x,C;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let l=Sc(p.voiceState),m=!!l.active,h=Number((C=l.timestamp)!=null?C:0);G.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-h<Zx&&setTimeout(()=>{var k,j;G.active||(G.manuallyDeactivated=!1,((j=(k=r.voiceRecognition)==null?void 0:k.provider)==null?void 0:j.type)==="runtype"?$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),ot("restore"),$.isVoiceActive()&&Es()}):Qa("restore"))},1e3)},yo=()=>$?Xf($.getMessages()).filter(l=>!l.__skipPersist):[],Mn=null,un=(l,m)=>{typeof console!="undefined"&&console.error(l,m)},Kr=(l,m)=>{let h=()=>{try{let j=l();return!j||typeof j.then!="function"?null:Promise.resolve(j).catch(O=>{un(m,O)})}catch(j){return un(m,j),null}},x=Mn,C=x?x.then(()=>{var j;return(j=h())!=null?j:void 0}):h();if(!C)return;let k=C.finally(()=>{Mn===k&&(Mn=null)});Mn=k};function Rr(l){if(!(c!=null&&c.save))return;let h={messages:l?Xf(l):$?yo():[],metadata:p,artifacts:On.artifacts,selectedArtifactId:On.selectedId};Kr(()=>c.save(h),"[AgentWidget] Failed to persist state:")}let an=null,kn=()=>fe.querySelector("#persona-scroll-container")||Ce,fn=()=>{an!==null&&(cancelAnimationFrame(an),an=null),En=!1},jc=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),Ko=!1,fn()},Nh=()=>Zn&&yl()&&(Ft()!=="anchor-top"||ir()),hl=()=>{let l=vt()||"Jump to latest",m=Nh();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),mr>0?(Bn.textContent=String(mr),Bn.style.display="",Vt.setAttribute("aria-label",`${l} (${mr} new)`)):(Bn.textContent="",Bn.style.display="none",Vt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},Uc=()=>{mr!==0&&(mr=0,hl())},yl=()=>en()?!xn.isFollowing():!Bo(Ce,V),_n=()=>{if(!Qt()||X){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==Te&&Te.appendChild(Vt),Gn();let m=Nr(Ce)>0&&yl();m?hl():Uc(),Vt.style.display=m?"":"none"},oa=()=>{xn.pause()&&(jc(),_n())},bo=()=>{xn.resume(),Uc(),_n()},xo=(l=!1)=>{en()&&xn.isFollowing()&&(!l&&!Zn||(ur!==null&&(cancelAnimationFrame(ur),ur=null),Ko=!0,ur=requestAnimationFrame(()=>{ur=null,Ko=!1,xn.isFollowing()&&Oh(kn(),l?220:140)})))},qc=(l,m,h,x=()=>!0)=>{let C=l.scrollTop,k=m(),j=k-C;if(fn(),Math.abs(j)<1){En=!0,l.scrollTop=k,Tn=l.scrollTop,En=!1;return}let O=performance.now();En=!0;let N=se=>1-Math.pow(1-se,3),le=se=>{if(!x()){fn();return}let Z=m();Z!==k&&(k=Z,j=k-C);let we=se-O,Fe=Math.min(we/h,1),_e=N(Fe),Ue=C+j*_e;l.scrollTop=Ue,Tn=l.scrollTop,Fe<1?an=requestAnimationFrame(le):(l.scrollTop=k,Tn=l.scrollTop,an=null,En=!1)};an=requestAnimationFrame(le)},Oh=(l,m=500)=>{let h=Nr(l)-l.scrollTop;if(Math.abs(h)<1){Tn=l.scrollTop;return}if(Math.abs(h)>=z){fn(),En=!0,l.scrollTop=Nr(l),Tn=l.scrollTop,En=!1;return}qc(l,()=>Nr(l),m,()=>xn.isFollowing())},zc=()=>{let l=kn();En=!0,l.scrollTop=Nr(l),Tn=l.scrollTop,En=!1,_n()},Vc=l=>{let m=0,h=l;for(;h&&h!==Ce;)m+=h.offsetTop,h=h.offsetParent;return m},Kc=()=>{var k;if(Fr()!=="last-user-turn")return!1;let l=(k=$==null?void 0:$.getMessages())!=null?k:[];if(l.length<2)return!1;let m=[...l].reverse().find(j=>j.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=Ce.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let C=Math.min(Math.max(0,Vc(x)-wr()),Nr(Ce));return En=!0,Ce.scrollTop=C,Tn=Ce.scrollTop,En=!1,Ft()==="follow"&&!Bo(Ce,V)&&xn.pause(),_n(),!0},Gc=l=>{In.style.height=`${Math.max(0,Math.round(l))}px`,vn&&(vn.spacerHeight=Math.max(0,l))},sa=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),fn(),vn=null,In.style.height="0px"},Fh=l=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var N;Ir=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=Ce.querySelector(`[data-message-id="${m}"]`);if(!h)return;let x=Vc(h),C=(N=vn==null?void 0:vn.spacerHeight)!=null?N:0,k=Ce.scrollHeight-C,{targetScrollTop:j,spacerHeight:O}=of({anchorOffsetTop:x,topOffset:wr(),viewportHeight:Ce.clientHeight,contentHeight:k});vn={initialSpacerHeight:O,contentHeightAtAnchor:k,spacerHeight:O},Gc(O),qc(Ce,()=>j,220)})},_h=()=>{if(en()){if(!xn.isFollowing()||Bo(Ce,1))return;xo(!Zn);return}if(vn&&vn.initialSpacerHeight>0){let l=Ce.scrollHeight-vn.spacerHeight,m=sf({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:l});m!==vn.spacerHeight&&Gc(m)}_n()},$h=l=>{let m=Ft();m==="follow"?(bo(),xo(!0)):m==="anchor-top"&&(fo=!1,ho=!0,Fh(l))},jh=()=>{if(Ft()==="anchor-top"){if(ho){fo=!1;return}fo=!0,sa(),bo(),xo(!0)}},Uh=l=>{let m=new Map;l.forEach(h=>{let x=J.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Go&&(Ft()!=="anchor-top"||ir())&&yl()&&(mr+=1,hl(),_n(),ao(mr===1?"1 new message below.":`${mr} new messages below.`))),h.role==="assistant"&&(x!=null&&x.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),J.clear(),m.forEach((h,x)=>{J.set(x,h)})},qh=(l,m,h)=>{var at,De,We,Ve,Qe,xt;let x=document.createElement("div"),k=(()=>{var Ne;let R=o.find(He=>He.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),j=(R,Ne)=>Ne==null?!1:typeof Ne=="string"?(R.textContent=Ne,!0):(R.appendChild(Ne),!0),O=new Set,N=new Set,le=o.some(R=>R.renderAskUserQuestion),se=[],Z=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,_e=[];if(m.forEach(R=>{var hn,$n,Je,Rt,jn,Xo,Qo,Yo,Zo,ks,Ls,Xt,es,Co,Ao,Qr,ts;O.add(R.id);let Ne=le&&Yr(R),He=Fe&&R.variant==="approval"&&!!R.approval,Ze=!Ne&&R.role==="assistant"&&!R.variant&&we&&za(R);if(!He&&pr.has(R.id)){let tt=l.querySelector(`#wrapper-${R.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),pr.delete(R.id)}if(!Ze&&Pr.has(R.id)){let tt=l.querySelector(`#wrapper-${R.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),Pr.delete(R.id)}let It=Yr(R)?`:${(hn=R.agentMetadata)!=null&&hn.askUserQuestionAnswered?"a":"u"}:${($n=R.agentMetadata)!=null&&$n.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",$e=Yg(R,vs)+It,Jt=Ne||He||Ze?null:ef(Lr,R.id,$e);if(Jt){x.appendChild(Jt.cloneNode(!0)),Yr(R)&&((Je=R.toolCall)!=null&&Je.id)&&((Rt=R.agentMetadata)==null?void 0:Rt.awaitingLocalTool)===!0&&!((jn=R.agentMetadata)!=null&&jn.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ns(R,r,Ke.composerOverlay));return}let Ct=null,cn=o.find(tt=>!!(R.variant==="reasoning"&&tt.renderReasoning||R.variant==="tool"&&tt.renderToolCall||!R.variant&&tt.renderMessage)),Wn=(Xo=r.layout)==null?void 0:Xo.messages;if(Yr(R)&&((Qo=R.agentMetadata)==null?void 0:Qo.askUserQuestionAnswered)===!0){Vr.delete(R.id);let tt=l.querySelector(`#wrapper-${R.id}`);tt==null||tt.removeAttribute("data-preserve-runtime");return}if(wa(R)&&((Zo=(Yo=r.features)==null?void 0:Yo.suggestReplies)==null?void 0:Zo.enabled)!==!1)return;if(Yr(R)&&((Ls=(ks=r.features)==null?void 0:ks.askUserQuestion)==null?void 0:Ls.enabled)!==!1){let tt=o.find(Ot=>typeof Ot.renderAskUserQuestion=="function");if(tt&&Tt.current){let Ot=Vr.get(R.id),Nt=Ot!==$e,Kt=null;if(Nt){let{payload:Ut,complete:yn}=Zr(R),Un=R.id,Hr=()=>{var mn;return(mn=Tt.current)==null?void 0:mn.getMessages().find(gn=>gn.id===Un)};Kt=tt.renderAskUserQuestion({message:R,payload:Ut,complete:yn,resolve:mn=>{var nr;let gn=Hr();gn&&((nr=Tt.current)==null||nr.resolveAskUserQuestion(gn,mn))},dismiss:()=>{var gn,nr,So;let mn=Hr();(gn=mn==null?void 0:mn.agentMetadata)!=null&&gn.awaitingLocalTool&&((nr=Tt.current)==null||nr.markAskUserQuestionResolved(mn),(So=Tt.current)==null||So.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let jt=Ot!=null;if(Nt&&Kt===null&&!jt){((Xt=R.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((es=R.agentMetadata)!=null&&es.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ns(R,r,Ke.composerOverlay));return}let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${R.id}`,gt.setAttribute("data-wrapper-id",R.id),gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),x.appendChild(gt),se.push({messageId:R.id,fingerprint:$e,bubble:Kt});return}else{((Co=R.agentMetadata)==null?void 0:Co.awaitingLocalTool)===!0&&!((Ao=R.agentMetadata)!=null&&Ao.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ns(R,r,Ke.composerOverlay));return}}else if(He){let tt=(Qr=o.find(jt=>typeof jt.renderApproval=="function"))!=null?Qr:s,Nt=pr.get(R.id)!==$e,Kt=null;if(Nt&&(tt!=null&&tt.renderApproval)){let jt=R.id,gt=(Ut,yn)=>{var Hr,mn,gn;let Un=(Hr=Tt.current)==null?void 0:Hr.getMessages().find(nr=>nr.id===jt);Un!=null&&Un.approval&&(Un.approval.toolType==="webmcp"?(mn=Tt.current)==null||mn.resolveWebMcpApproval(Un.id,Ut):(gn=Tt.current)==null||gn.resolveApproval(Un.approval,Ut,yn))};Kt=tt.renderApproval({message:R,defaultRenderer:()=>Xi(R,r),config:r,approve:Ut=>gt("approved",Ut),deny:Ut=>gt("denied",Ut)})}if(Nt&&Kt===null){let jt=l.querySelector(`#wrapper-${R.id}`);jt==null||jt.removeAttribute("data-preserve-runtime"),pr.delete(R.id),Ct=Xi(R,r)}else{let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-${R.id}`,jt.setAttribute("data-wrapper-id",R.id),jt.setAttribute("data-approval-plugin-stub","true"),jt.setAttribute("data-preserve-runtime","true"),x.appendChild(jt),_e.push({messageId:R.id,fingerprint:$e,bubble:Kt});return}}else if(cn)if(R.variant==="reasoning"&&R.reasoning&&cn.renderReasoning){if(!Pe)return;Ct=cn.renderReasoning({message:R,defaultRenderer:()=>gc(R,r),config:r})}else if(R.variant==="tool"&&R.toolCall&&cn.renderToolCall){if(!Ie)return;Ct=cn.renderToolCall({message:R,defaultRenderer:()=>hc(R,r),config:r})}else cn.renderMessage&&(Ct=cn.renderMessage({message:R,defaultRenderer:()=>{let tt=Js(R,h,Wn,r.messageActions,be,{loadingIndicatorRenderer:k,widgetConfig:r});return R.role!=="user"&&wc(tt,R,r,$),tt},config:r}));if(!Ct&&Ze){let tt=rl(R);if(tt){let Ot=Pr.get(R.id),Nt=Ot!==$e,Kt=r.wrapComponentDirectiveInBubble!==!1,jt=null;if(Nt){let gt=nl(tt,{config:r,message:R,transform:h});if(gt)if(Kt){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let yn=document.createElement("div");yn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",yn.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(yn)}Ut.appendChild(gt),jt=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),Ut.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let yn=document.createElement("div");yn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",yn.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(yn)}Ut.appendChild(gt),jt=Ut}}if(jt||Ot!=null){let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${R.id}`,gt.setAttribute("data-wrapper-id",R.id),gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),Kt||gt.classList.add("persona-w-full"),x.appendChild(gt),Z.push({messageId:R.id,fingerprint:$e,bubble:jt});return}}}if(!Ct)if(R.variant==="reasoning"&&R.reasoning){if(!Pe)return;Ct=gc(R,r)}else if(R.variant==="tool"&&R.toolCall){if(!Ie)return;Ct=hc(R,r)}else if(R.variant==="approval"&&R.approval){if(r.approval===!1)return;Ct=Xi(R,r)}else{let tt=(ts=r.layout)==null?void 0:ts.messages;tt!=null&&tt.renderUserMessage&&R.role==="user"?Ct=tt.renderUserMessage({message:R,config:r,streaming:!!R.streaming}):tt!=null&&tt.renderAssistantMessage&&R.role==="assistant"?Ct=tt.renderAssistantMessage({message:R,config:r,streaming:!!R.streaming}):Ct=Js(R,h,tt,r.messageActions,be,{loadingIndicatorRenderer:k,widgetConfig:r}),R.role!=="user"&&Ct&&wc(Ct,R,r,$)}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${R.id}`,Dt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Dt.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&Dt.classList.add("persona-w-full"),Dt.appendChild(Ct),tf(Lr,R.id,$e,Dt),x.appendChild(Dt)}),Ke.composerOverlay&&Ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let He=Ne.getAttribute("data-persona-ask-sheet-for");He&&!N.has(He)&&ko(Ke.composerOverlay,He)}),(De=(at=r.features)==null?void 0:at.toolCallDisplay)!=null&&De.grouped){let R=[],Ne=[];m.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&Ie){Ne.push(He);return}Ne.length>1&&R.push(Ne),Ne=[]}),Ne.length>1&&R.push(Ne),R.forEach((He,Ze)=>{var hn,$n;let It=He.map(Je=>Array.from(x.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Je.id)).filter(Je=>!!Je);if(It.length<2)return;let $e=document.createElement("div");$e.className="persona-flex",$e.id=`wrapper-tool-group-${Ze}-${He[0].id}`,$e.setAttribute("data-wrapper-id",`tool-group-${Ze}-${He[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${He.length} tools`,Wn=($n=(hn=r.toolCall)==null?void 0:hn.renderGroupedSummary)==null?void 0:$n.call(hn,{messages:He,toolCalls:He.map(Je=>Je.toolCall).filter(Je=>!!Je),defaultSummary:cn,config:r});j(Ct,Wn)||(Ct.textContent=cn);let Dt=document.createElement("div");Dt.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,Dt),$e.appendChild(Jt),It[0].before($e),It.forEach((Je,Rt)=>{let jn=document.createElement("div");jn.className="persona-tool-group-item persona-relative",jn.setAttribute("data-persona-tool-group-item","true"),Rt<It.length-1&&jn.setAttribute("data-persona-tool-group-connector","true"),jn.appendChild(Je),Dt.appendChild(jn)})})}nf(Lr,O);let Ue=m.some(R=>R.role==="assistant"&&R.streaming),ze=m[m.length-1],mt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Zn&&m.some(R=>R.role==="user")&&!Ue&&!mt){let R={config:r,streaming:!0,location:"standalone",defaultRenderer:us},Ne=o.find(Ze=>Ze.renderLoadingIndicator),He=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(He=Ne.renderLoadingIndicator(R)),He===null&&((We=r.loadingIndicator)!=null&&We.render)&&(He=r.loadingIndicator.render(R)),He===null&&(He=us()),He){let Ze=document.createElement("div"),It=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;Ze.className=It?["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(" "),Ze.setAttribute("data-typing-indicator","true"),Ze.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ze.appendChild(He);let $e=document.createElement("div");$e.className="persona-flex",$e.id="wrapper-typing-indicator",$e.setAttribute("data-wrapper-id","typing-indicator"),$e.appendChild(Ze),x.appendChild($e)}}if(!Zn&&m.length>0){let R=m[m.length-1],Ne={config:r,lastMessage:R,messageCount:m.length},He=o.find(It=>It.renderIdleIndicator),Ze=null;if(He!=null&&He.renderIdleIndicator&&(Ze=He.renderIdleIndicator(Ne)),Ze===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(Ze=r.loadingIndicator.renderIdle(Ne)),Ze){let It=document.createElement("div"),$e=((xt=r.loadingIndicator)==null?void 0:xt.showBubble)!==!1;It.className=$e?["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(" "),It.setAttribute("data-idle-indicator","true"),It.appendChild(Ze);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(It),x.appendChild(Jt)}}if(Pi(l,x),se.length>0)for(let{messageId:R,fingerprint:Ne,bubble:He}of se){let Ze=l.querySelector(`#wrapper-${R}`);Ze&&He!==null&&(Ze.replaceChildren(He),Ze.setAttribute("data-bubble-fp",Ne),Vr.set(R,Ne))}if(Vr.size>0)for(let R of Vr.keys())O.has(R)||Vr.delete(R);if(Z.length>0)for(let{messageId:R,fingerprint:Ne,bubble:He}of Z){let Ze=l.querySelector(`#wrapper-${R}`);Ze&&He!==null&&(Ze.replaceChildren(He),Ze.setAttribute("data-bubble-fp",Ne),Pr.set(R,Ne))}if(Pr.size>0)for(let R of Pr.keys())O.has(R)||Pr.delete(R);if(_e.length>0)for(let{messageId:R,fingerprint:Ne,bubble:He}of _e){let Ze=l.querySelector(`#wrapper-${R}`);Ze&&He!==null&&(Ze.replaceChildren(He),Ze.setAttribute("data-bubble-fp",Ne),pr.set(R,Ne))}if(pr.size>0)for(let R of pr.keys())O.has(R)||pr.delete(R)},aa=(l,m,h)=>{qh(l,m,h),uo()},ia=null,zh=()=>{var h;if(ia)return;let l=x=>{let C=x.composedPath();C.includes(fe)||lt&&C.includes(lt)||$t(!1,"user")};ia=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Jc=()=>{var m;if(!ia)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",ia,!0),ia=null};ct.push(()=>Jc());let la=null,Vh=()=>{var h;if(la)return;let l=x=>{x.key==="Escape"&&(x.isComposing||$t(!1,"user"))};la=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Xc=()=>{var m;if(!la)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",la,!0),la=null};ct.push(()=>Xc());let ca=!1,Qc=new Set,Kh=()=>{var m,h,x,C;let l=(x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:x.streamAnimation;return l||((C=r.features)==null?void 0:C.streamAnimation)},As=()=>{var mt,at,De,We;if(!L())return;let l=Ke.peekBanner,m=Ke.peekTextNode;if(!l||!m)return;if(_){l.classList.remove("persona-pill-peek--visible");return}let h=(mt=$==null?void 0:$.getMessages())!=null?mt:[],x;for(let Ve=h.length-1;Ve>=0;Ve--){let Qe=h[Ve];if(Qe.role==="assistant"&&Qe.content){x=Qe;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let C=x.content,k=!!x.streaming,j=Kh(),O=Bi(j),N=O.type!=="none"?Vs(O.type,j==null?void 0:j.plugins):null,le=((at=N==null?void 0:N.isAnimating)==null?void 0:at.call(N,x))===!0,se=N!==null&&(k||le);se&&N&&!Qc.has(N.name)&&(Oi(N,e),Qc.add(N.name));let Z=se&&(N!=null&&N.containerClass)?N.containerClass:null,we=(De=m.dataset.personaPeekStreamClass)!=null?De:null;we&&we!==Z&&(m.classList.remove(we),delete m.dataset.personaPeekStreamClass),Z&&we!==Z&&(m.classList.add(Z),m.dataset.personaPeekStreamClass=Z),se?(m.style.setProperty("--persona-stream-step",`${O.speed}ms`),m.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Fe=se?Di(C,O.buffer,N,x,k):C;if(se&&O.placeholder==="skeleton"&&k&&(!Fe||!Fe.trim())){let Ve=document.createElement("div"),Qe=Ha();Qe.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Qe),Pi(m,Ve)}else{let Ve=Math.max(0,Fe.length-100),Qe=Fe.length>100?Fe.slice(-100):Fe,xt=Br(Qe);if(!se||!N){let R=Fe.length>100?`\u2026${Qe}`:Qe;m.textContent!==R&&(m.textContent=R)}else{let R=xt;(N.wrap==="char"||N.wrap==="word")&&(R=Wa(xt,N.wrap,`peek-${x.id}`,{skipTags:N.skipTags,startIndex:Ve}));let Ne=document.createElement("div");if(Ne.innerHTML=R,N.useCaret&&Qe.length>0){let He=Ni(),Ze=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),It=Ze[Ze.length-1];It!=null&&It.parentNode?It.parentNode.insertBefore(He,It.nextSibling):Ne.appendChild(He)}Pi(m,Ne),(We=N.onAfterRender)==null||We.call(N,{container:m,bubble:l,messageId:x.id,message:x,speed:O.speed,duration:O.duration})}}let ze=Zn||ca;l.classList.toggle("persona-pill-peek--visible",ze)};if(L()){let l=Ke.peekBanner;if(l){let x=C=>{C.preventDefault(),C.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",x),ct.push(()=>{l.removeEventListener("pointerdown",x)})}let m=()=>{ca||(ca=!0,As())},h=()=>{ca&&(ca=!1,As())};Q.addEventListener("pointerenter",m),Q.addEventListener("pointerleave",h),ct.push(()=>{Q.removeEventListener("pointerenter",m),Q.removeEventListener("pointerleave",h)}),lt&&(lt.addEventListener("pointerenter",m),lt.addEventListener("pointerleave",h),ct.push(()=>{lt.removeEventListener("pointerenter",m),lt.removeEventListener("pointerleave",h)}))}let Gh=l=>{var we,Fe,_e,Ue,ze,mt,at,De;let m=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(_e=m.expandedSize)!=null?_e:"anchored",x=(Ue=m.bottomOffset)!=null?Ue:"16px",C=m.collapsedMaxWidth,k=(ze=m.expandedMaxWidth)!=null?ze:"880px",j=(mt=m.expandedTopOffset)!=null?mt:"5vh",O=(at=m.modalMaxWidth)!=null?at:"880px",N=(De=m.modalMaxHeight)!=null?De:"min(90vh, 800px)",le="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Z=fe.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",lt){let We=lt.style;We.bottom=x,We.width=C!=null?C:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=O,Z.maxWidth=le,Z.maxHeight=N,Z.height=N;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${x} + ${se})`,Z.top=j,Z.width=k,Z.maxWidth=le}},da=()=>{var N,le,se,Z,we,Fe,_e,Ue;if(!F())return;if(L()){let mt=(se=((le=(N=r.launcher)==null?void 0:N.composerBar)!=null?le:{}).expandedSize)!=null?se:"anchored",at=_?"expanded":"collapsed";fe.dataset.state=at,fe.dataset.expandedSize=mt,lt&&(lt.dataset.state=at,lt.dataset.expandedSize=mt),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Gh(_),Te.style.display=_?"flex":"none",go(),_?(zh(),Vh()):(Jc(),Xc()),As();return}let l=rn(r),m=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,x=(Ue=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ue:!0,C=m.innerWidth<=h,k=x&&C&&H,j=Vn(r).reveal;_?(fe.style.removeProperty("display"),fe.style.display=l?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0"),Q.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":ln&&(ln.style.display="none")):(l?l&&(j==="overlay"||j==="push")&&!k?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100"),Q.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=l?"none":"":ln&&(ln.style.display=l?"none":""))},$t=(l,m="user")=>{var k,j;if(!F()||_===l)return;let h=_;_=l,da();let x=(()=>{var _e,Ue,ze,mt,at,De,We,Ve,Qe,xt;let O=(Ue=(_e=r.launcher)==null?void 0:_e.sidebarMode)!=null?Ue:!1,N=(ze=e.ownerDocument.defaultView)!=null?ze:window,le=(at=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?at:!0,se=(We=(De=r.launcher)==null?void 0:De.mobileBreakpoint)!=null?We:640,Z=N.innerWidth<=se,we=rn(r)&&le&&Z,Fe=L()&&((xt=(Qe=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return O||le&&Z&&H||we||Fe})();if(_&&x){if(!on){let O=e.getRootNode(),N=O instanceof ShadowRoot?O.host:e.closest(".persona-host");N&&(on=rc(N,(j=(k=r.launcher)==null?void 0:k.zIndex)!=null?j:Cn))}sn||(sn=oc(e.ownerDocument))}else _||(on==null||on(),on=null,sn==null||sn(),sn=null);_&&(pa(),Kc()||(Ft()==="follow"?xo(!0):zc()));let C={open:_,source:m,timestamp:Date.now()};_&&!h?i.emit("widget:opened",C):!_&&h&&i.emit("widget:closed",C),i.emit("widget:state",{open:_,launcherEnabled:H,voiceActive:G.active,streaming:$.isStreaming()})},bl=l=>{ge(l?"stop":"send"),D&&(D.disabled=l),Vo.buttons.forEach(m=>{m.disabled=l}),Be.dataset.personaComposerStreaming=l?"true":"false",Be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},xl=()=>{G.active||xe&&xe.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>xl(),200)});let Yc=()=>{var h,x,C,k,j,O,N,le,se,Z,we;xr.textContent=(x=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?x:"Hello \u{1F44B}",vr.textContent=(k=(C=r.copy)==null?void 0:C.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",xe.placeholder=(O=(j=r.copy)==null?void 0:j.inputPlaceholder)!=null?O:"How can I help...";let l=Ce.querySelector("[data-persona-intro-card]");if(l){let Fe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Ce.classList.remove("persona-gap-3"),Ce.classList.add("persona-gap-6")):(Ce.classList.remove("persona-gap-6"),Ce.classList.add("persona-gap-3"))}!((se=(le=r.sendButton)==null?void 0:le.useIcon)!=null&&se)&&!($!=null&&$.isStreaming())&&(ue.textContent=(we=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?we:"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(m=>({...m,sessionId:l}))}});let Jo=null,Jh=()=>{Jo==null&&(Jo=setInterval(()=>{let l=et.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Jo),Jo=null;return}let m=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=pi(m-x))})},100))},vl=(l,m)=>{if(Object.is(l,m))return!0;if(l===null||m===null||typeof l!="object"||typeof m!="object")return!1;if(Array.isArray(l)||Array.isArray(m))return!Array.isArray(l)||!Array.isArray(m)||l.length!==m.length?!1:l.every((j,O)=>vl(j,m[O]));let h=l,x=m,C=Object.keys(h),k=Object.keys(x);return C.length===k.length&&C.every(j=>Object.prototype.hasOwnProperty.call(x,j)&&vl(h[j],x[j]))},Zc=l=>{let{content:m,rawContent:h,llmContent:x,...C}=l;return C},wl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!za(l),Xh=(l,m,h)=>{if(l.length!==m.length)return!1;let x=l[h.index],C=m[h.index];return!x||!C||x.id!==h.id||C.id!==h.id?!1:(!Object.is(x.content,C.content)||!Object.is(x.rawContent,C.rawContent)||!Object.is(x.llmContent,C.llmContent))&&wl(x)&&wl(C)&&vl(Zc(x),Zc(C))},ed=null,Ss=null,Gr=null,Jr=null,Ja=l=>{var C,k;ed=l;let m,h;Ss=null;for(let j=l.length-1;j>=0;j-=1){let O=l[j];if(!m&&O.role==="user"&&(m=O),!h&&O.role==="assistant"&&(h=O),!Ss&&wl(O)&&(Ss={index:j,id:O.id}),m&&h&&Ss)break}aa(et,l,te),Jh(),xs(l),xo(!Zn),Uh(l),l.length===0&&(sa(),fo=!0,ho=!1),!ws||Go?(ws=!0,Cs=(C=m==null?void 0:m.id)!=null?C:null,st=(k=h==null?void 0:h.id)!=null?k:null):m&&m.id!==Cs?(Cs=m.id,$h(m.id)):h&&h.id!==st&&jh(),h&&(st=h.id);let x=G.lastUserMessageId;m&&m.id!==x&&(G.lastUserMessageId=m.id,i.emit("user:message",m)),G.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Rr(l),As()},Cl=()=>{Jr!==null&&(cancelAnimationFrame(Jr),Jr=null);let l=Gr;Gr=null,l&&Ja(l)},td=()=>{Jr!==null&&cancelAnimationFrame(Jr),Jr=null,Gr=null},Qh=l=>{let m=Gr!=null?Gr:ed;if(Zn&&m&&Ss&&Xh(m,l,Ss)){Gr=l,Jr===null&&(Jr=requestAnimationFrame(()=>{Jr=null;let h=Gr;Gr=null,h&&Ja(h)}));return}if(l.length===0){td(),Ja(l);return}Cl(),Ja(l)};$=new js(r,{onMessagesChanged(l){Qh(l)},onStatusChanged(l){var x;let m=(x=r.statusIndicator)!=null?x:{};Ht(bn,(C=>{var k,j,O,N,le,se;return C==="idle"?(k=m.idleText)!=null?k:nn.idle:C==="connecting"?(j=m.connectingText)!=null?j:nn.connecting:C==="connected"?(O=m.connectedText)!=null?O:nn.connected:C==="error"?(N=m.errorText)!=null?N:nn.error:C==="paused"?(le=m.pausedText)!=null?le:nn.paused:C==="resuming"?(se=m.resumingText)!=null?se:nn.resuming:nn[C]})(l),m,l)},onStreamingChanged(l){l||(($==null?void 0:$.getMessages().length)===0?td():Cl()),Zn=l,bl(l),$&&aa(et,$.getMessages(),te),l||xo(!0),_n(),ao(l?"Responding\u2026":"Response complete."),As()},onVoiceStatusChanged(l){var m,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Xr(),Es();break;case"processing":Xr(),ny();break;case"speaking":Xr(),ry();break;default:l==="idle"&&$.isBargeInActive()?(Xr(),Es(),D==null||D.setAttribute("aria-label","End voice session")):(G.active=!1,Xr(),ot("system"),dt());break}},onArtifactsState(l){On=l,Er(),Rr()},onReconnect(l){var x;let{executionId:m,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:h,attempt:(x=l.attempt)!=null?x:1}):i.emit("stream:resumed",{executionId:m,after:h})}}),Tt.current=$,ct.push(()=>$.cancel());let Al=null;if($.onReadAloudChange((l,m)=>{var C;co=l,po=m,uo();let h=l!=null?l:Al;l&&(Al=l);let x=h&&(C=$.getMessages().find(k=>k.id===h))!=null?C:null;i.emit("message:read-aloud",{messageId:h,message:x,state:m,timestamp:Date.now()}),m==="idle"&&(Al=null)}),ws=!0,((fp=(gp=r.voiceRecognition)==null?void 0:gp.provider)==null?void 0:fp.type)==="runtype")try{$.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&$.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(K||r.onSSEEvent)&&$.setSSEEventCallback((l,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,m),Y==null||Y.processEvent(l,m),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let nd=()=>{r.resume&&typeof r.reconnectStream=="function"&&$.resumeFromHandle(r.resume)};u?u.then(l=>{var m,h,x;if(l){if(l.metadata&&(p=Sc(l.metadata),P.syncFromMetadata()),(m=l.messages)!=null&&m.length){Go=!0;try{$.hydrateMessages(l.messages)}finally{Go=!1}}(h=l.artifacts)!=null&&h.length&&$.hydrateArtifacts(l.artifacts,(x=l.selectedArtifactId)!=null?x:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>nd()):nd();let rd=()=>{var m,h,x;!L()||_||!((x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||x)||$t(!0,"auto")},od=l=>{var C;if(l.preventDefault(),$.isStreaming()){$.cancel(),Y==null||Y.reset(),ke==null||ke.update();return}let m=xe.value.trim(),h=(C=St==null?void 0:St.hasAttachments())!=null?C:!1;if(!m&&!h)return;rd();let x;h&&(x=[],x.push(...St.getContentParts()),m&&x.push(Ta(m))),xe.value="",xe.style.height="auto",Xa(),$.sendMessage(m,{contentParts:x}),h&&St.clearAttachments()},Yh=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},Sl={...Ii},Tl=!1,Xa=()=>{Sl={...Ii}},Zh=()=>$.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),ey=l=>{if(!xe)return;Tl=!0,xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),Tl=!1;let m=xe.value.length;xe.setSelectionRange(m,m)},sd=()=>{Tl||Xa()},ad=l=>{if(xe){if(Yh()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=xe.selectionStart===0&&xe.selectionEnd===0,h=Qg({direction:l.key==="ArrowUp"?"up":"down",history:Zh(),currentValue:xe.value,atStart:m,state:Sl});if(Sl=h.state,h.handled){l.preventDefault(),h.value!==void 0&&ey(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}Xa(),l.preventDefault(),ue.click()}}},id=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(Te)&&($.cancel(),Y==null||Y.reset(),ke==null||ke.update(),Xa(),l.preventDefault(),l.stopImmediatePropagation())},ld=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!St)return;let m=tv(l.clipboardData);m.length!==0&&(l.preventDefault(),await St.handleFiles(m))},er=null,Wr=!1,Ts=null,ut=null,cd=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qa=(l="user")=>{var k,j,O,N,le,se,Z;if(Wr||$.isStreaming())return;let m=cd();if(!m)return;er=new m;let x=(j=((k=r.voiceRecognition)!=null?k:{}).pauseDuration)!=null?j:2e3;er.continuous=!0,er.interimResults=!0,er.lang="en-US";let C=xe.value;er.onresult=we=>{let Fe="",_e="";for(let ze=0;ze<we.results.length;ze++){let mt=we.results[ze],at=mt[0].transcript;mt.isFinal?Fe+=at+" ":_e=at}let Ue=C+Fe+_e;xe.value=Ue,Ts&&clearTimeout(Ts),(Fe||_e)&&(Ts=window.setTimeout(()=>{let ze=xe.value.trim();ze&&er&&Wr&&(vo(),xe.value="",xe.style.height="auto",$.sendMessage(ze,{viaVoice:!0}))},x))},er.onerror=we=>{we.error!=="no-speech"&&vo()},er.onend=()=>{if(Wr){let we=xe.value.trim();we&&we!==C.trim()&&(xe.value="",xe.style.height="auto",$.sendMessage(we,{viaVoice:!0})),vo()}};try{if(er.start(),Wr=!0,G.active=!0,l!=="system"&&(G.manuallyDeactivated=!1),ot(l),dt(),D){let we=(O=r.voiceRecognition)!=null?O:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(N=we.iconName)!=null?N:"mic",iconSize:parseFloat((Z=(se=we.iconSize)!=null?se:(le=r.sendButton)==null?void 0:le.size)!=null?Z:"40")||24};let Fe=we.recordingBackgroundColor,_e=we.recordingIconColor,Ue=we.recordingBorderColor;if(D.classList.add("persona-voice-recording"),D.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=_e!=null?_e:"var(--persona-voice-recording-indicator, #ffffff)",_e){let ze=D.querySelector("svg");ze&&ze.setAttribute("stroke",_e)}Ue&&(D.style.borderColor=Ue),D.setAttribute("aria-label","Stop voice recognition")}}catch{vo("system")}},vo=(l="user")=>{if(Wr){if(Wr=!1,Ts&&(clearTimeout(Ts),Ts=null),er){try{er.stop()}catch{}er=null}if(G.active=!1,ot(l),dt(),D){if(D.classList.remove("persona-voice-recording"),ut){D.style.backgroundColor=ut.backgroundColor,D.style.color=ut.color,D.style.borderColor=ut.borderColor;let m=D.querySelector("svg");m&&m.setAttribute("stroke",ut.color||"currentColor"),ut=null}D.setAttribute("aria-label","Start voice recognition")}}},ty=(l,m)=>{var at,De,We,Ve,Qe,xt,R,Ne,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((at=l==null?void 0:l.provider)==null?void 0:at.type)==="runtype",C=((De=l==null?void 0:l.provider)==null?void 0:De.type)==="custom";if(!(h||x||C))return null;let j=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let N=(We=l==null?void 0:l.iconName)!=null?We:"mic",le=(Ve=m==null?void 0:m.size)!=null?Ve:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:le,Z=parseFloat(se)||24,we=(xt=l==null?void 0:l.backgroundColor)!=null?xt:m==null?void 0:m.backgroundColor,Fe=(R=l==null?void 0:l.iconColor)!=null?R:m==null?void 0:m.textColor;O.style.width=se,O.style.height=se,O.style.minWidth=se,O.style.minHeight=se,O.style.fontSize="18px",O.style.lineHeight="1",Fe?O.style.color=Fe:O.style.color="var(--persona-text, #111827)";let Ue=he(N,Z,Fe||"currentColor",1.5);Ue?O.appendChild(Ue):O.textContent="\u{1F3A4}",we?O.style.backgroundColor=we:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),j.appendChild(O);let ze=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((He=l==null?void 0:l.showTooltip)!=null?He:!1)&&ze){let Ze=b("div","persona-send-button-tooltip");Ze.textContent=ze,j.appendChild(Ze)}return{micButton:O,micButtonWrapper:j}},El=()=>{var m,h,x,C,k;if(!D||ut)return;let l=(m=r.voiceRecognition)!=null?m:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((k=(C=l.iconSize)!=null?C:(x=r.sendButton)==null?void 0:x.size)!=null?k:"40")||24}},Ml=(l,m)=>{var k,j,O,N,le;if(!D)return;let h=D.querySelector("svg");h&&h.remove();let x=(le=ut==null?void 0:ut.iconSize)!=null?le:parseFloat((N=(O=(k=r.voiceRecognition)==null?void 0:k.iconSize)!=null?O:(j=r.sendButton)==null?void 0:j.size)!=null?N:"40")||24,C=he(l,x,m,1.5);C&&D.appendChild(C)},Ya=()=>{D&&D.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Es=()=>{var C;if(!D)return;El();let l=(C=r.voiceRecognition)!=null?C:{},m=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Ya(),D.classList.add("persona-voice-recording"),D.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let k=D.querySelector("svg");k&&k.setAttribute("stroke",h)}x&&(D.style.borderColor=x),D.setAttribute("aria-label","Stop voice recognition")},ny=()=>{var O,N,le,se,Z,we,Fe,_e;if(!D)return;El();let l=(O=r.voiceRecognition)!=null?O:{},m=$.getVoiceInterruptionMode(),h=(N=l.processingIconName)!=null?N:"loader",x=(se=(le=l.processingIconColor)!=null?le:ut==null?void 0:ut.color)!=null?se:"",C=(we=(Z=l.processingBackgroundColor)!=null?Z:ut==null?void 0:ut.backgroundColor)!=null?we:"",k=(_e=(Fe=l.processingBorderColor)!=null?Fe:ut==null?void 0:ut.borderColor)!=null?_e:"";Ya(),D.classList.add("persona-voice-processing"),D.style.backgroundColor=C,D.style.borderColor=k;let j=x||"currentColor";D.style.color=j,Ml(h,j),D.setAttribute("aria-label","Processing voice input"),m==="none"&&(D.style.cursor="default")},ry=()=>{var le,se,Z,we,Fe,_e,Ue,ze,mt,at,De,We;if(!D)return;El();let l=(le=r.voiceRecognition)!=null?le:{},m=$.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(se=l.speakingIconName)!=null?se:h,C=(_e=l.speakingIconColor)!=null?_e:m==="barge-in"?(we=(Z=l.recordingIconColor)!=null?Z:ut==null?void 0:ut.color)!=null?we:"":(Fe=ut==null?void 0:ut.color)!=null?Fe:"",k=(mt=l.speakingBackgroundColor)!=null?mt:m==="barge-in"?(Ue=l.recordingBackgroundColor)!=null?Ue:"var(--persona-voice-recording-bg, #ef4444)":(ze=ut==null?void 0:ut.backgroundColor)!=null?ze:"",j=(We=l.speakingBorderColor)!=null?We:m==="barge-in"?(at=l.recordingBorderColor)!=null?at:"":(De=ut==null?void 0:ut.borderColor)!=null?De:"";Ya(),D.classList.add("persona-voice-speaking"),D.style.backgroundColor=k,D.style.borderColor=j;let O=C||"currentColor";D.style.color=O,Ml(x,O);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";D.setAttribute("aria-label",N),m==="none"&&(D.style.cursor="default"),m==="barge-in"&&D.classList.add("persona-voice-recording")},Xr=()=>{var l,m,h;D&&(Ya(),ut&&(D.style.backgroundColor=(l=ut.backgroundColor)!=null?l:"",D.style.color=(m=ut.color)!=null?m:"",D.style.borderColor=(h=ut.borderColor)!=null?h:"",Ml(ut.iconName,ut.color||"currentColor"),ut=null),D.style.cursor="",D.setAttribute("aria-label","Start voice recognition"))},Za=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let h=$.getVoiceStatus(),x=$.getVoiceInterruptionMode();if(x==="none"&&(h==="processing"||h==="speaking"))return;if(x==="cancel"&&(h==="processing"||h==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),ot("user"),Xr()});return}$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),G.manuallyDeactivated=!$.isVoiceActive(),dt(),ot("user"),$.isVoiceActive()?Es():Xr()});return}if(Wr){let h=xe.value.trim();G.manuallyDeactivated=!0,dt(),vo("user"),h&&(xe.value="",xe.style.height="auto",$.sendMessage(h))}else G.manuallyDeactivated=!1,dt(),Qa("user")};Ar=Za,D&&(D.addEventListener("click",Za),ct.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Xr()):vo("system"),D&&D.removeEventListener("click",Za)}));let oy=i.on("assistant:complete",()=>{Oe&&(G.active||G.manuallyDeactivated||Oe==="assistant"&&!G.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!G.active&&!G.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),ot("auto"),$.isVoiceActive()&&Es()}):Qa("auto"))},600))});ct.push(oy);let sy=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ct.push(sy);let dd=()=>{$t(!_,"user")},Zt=null,ln=null;if(H&&!L()){let{instance:l,element:m}=cc({config:r,plugins:o,onToggle:dd});Zt=l,l||(ln=m)}Zt?e.appendChild(Zt.element):ln&&e.appendChild(ln),da(),xs(),Yc(),bl($.isStreaming()),Kc()||(Ft()==="follow"?xo(!0):zc()),fl(),I&&(!H||L()?setTimeout(()=>xl(),0):_&&setTimeout(()=>xl(),200));let pa=()=>{var N,le,se,Z,we,Fe,_e,Ue,ze,mt,at,De,We,Ve,Qe,xt,R,Ne,He,Ze,It,$e;if(L()){Gn(),da();return}let l=rn(r),m=(le=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?le:!1,h=l||m||((Z=(se=r.launcher)==null?void 0:se.fullHeight)!=null?Z:!1),x=(we=e.ownerDocument.defaultView)!=null?we:window,C=(_e=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?_e:!0,k=(ze=(Ue=r.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?ze:640,j=x.innerWidth<=k,O=C&&j&&H;try{if(O){go(),Ho(e,r);return}if(U&&(U=!1,go(),Ho(e,r)),!H&&!l){Q.style.height="",Q.style.width="";return}if(!m&&!l){let Jt=(at=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?at:r==null?void 0:r.launcherWidth,Ct=Jt!=null?Jt:zn;Q.style.width=Ct,Q.style.maxWidth=Ct}if(zo(),!h){let Jt=x.innerHeight,Ct=64,cn=(We=(De=r.launcher)==null?void 0:De.heightOffset)!=null?We:0,Wn=Math.max(200,Jt-Ct),Dt=Math.min(640,Wn),hn=Math.max(200,Dt-cn);Q.style.height=`${hn}px`}}finally{if(Gn(),da(),_&&H){let Ct=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((xt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),cn=(Ne=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?Ne:!1,Wn=(Ze=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?Ze:!0,Dt=rn(r)&&Wn&&Ct,hn=cn||Wn&&Ct&&H||Dt;if(hn&&!sn){let $n=e.getRootNode(),Je=$n instanceof ShadowRoot?$n.host:e.closest(".persona-host");Je&&!on&&(on=rc(Je,($e=(It=r.launcher)==null?void 0:It.zIndex)!=null?$e:Cn)),sn=oc(e.ownerDocument)}else hn||(on==null||on(),on=null,sn==null||sn(),sn=null)}}};pa();let pd=(hp=e.ownerDocument.defaultView)!=null?hp:window;if(pd.addEventListener("resize",pa),ct.push(()=>pd.removeEventListener("resize",pa)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Gn()});l.observe(Be),ct.push(()=>l.disconnect())}Tn=Ce.scrollTop;let ud=Nr(Ce),ay=()=>{let l=Ce.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:Ce.ownerDocument.getSelection()},kl=()=>rf(ay(),Ce),md=()=>{let l=Ce.scrollTop,m=Nr(Ce),h=m<ud;if(ud=m,!en()){Tn=l,_n();return}let{action:x,nextLastScrollTop:C}=Wi({following:xn.isFollowing(),currentScrollTop:l,lastScrollTop:Tn,nearBottom:Bo(Ce,V),userScrollThreshold:w,isAutoScrolling:En||Ko||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Tn=C,x==="resume"){kl()||bo();return}x==="pause"&&oa()};if(Ce.addEventListener("scroll",md,{passive:!0}),ct.push(()=>Ce.removeEventListener("scroll",md)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{_h()});l.observe(et),l.observe(Ce),ct.push(()=>l.disconnect())}let gd=()=>{en()&&xn.isFollowing()&&kl()&&oa()},fd=Ce.ownerDocument;fd.addEventListener("selectionchange",gd),ct.push(()=>{fd.removeEventListener("selectionchange",gd)});let iy=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),hd=l=>{ar()&&en()&&xn.isFollowing()&&iy.has(l.key)&&oa()},yd=l=>{if(!ar()||!en()||!xn.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&oa()};Ce.addEventListener("keydown",hd),Ce.addEventListener("focusin",yd),ct.push(()=>{Ce.removeEventListener("keydown",hd),Ce.removeEventListener("focusin",yd)});let bd=l=>{if(!en())return;let m=Hi({following:xn.isFollowing(),deltaY:l.deltaY,nearBottom:Bo(Ce,V),resumeWhenNearBottom:!0});m==="pause"?oa():m==="resume"&&!kl()&&bo()};Ce.addEventListener("wheel",bd,{passive:!0}),ct.push(()=>Ce.removeEventListener("wheel",bd)),Vt.addEventListener("click",()=>{sa(),Ce.scrollTop=Ce.scrollHeight,Tn=Ce.scrollTop,bo(),xo(!0),_n()}),ct.push(()=>Vt.remove()),ct.push(()=>{jc(),sa()});let xd=()=>{qe&&(kr&&(qe.removeEventListener("click",kr),kr=null),F()?(qe.style.display="",kr=()=>{$t(!1,"user")},qe.addEventListener("click",kr)):qe.style.display="none")};xd(),(()=>{let{clearChatButton:l}=Ke;l&&l.addEventListener("click",()=>{$.clearMessages(),Lr.clear(),bo(),ko(Ke.composerOverlay);try{localStorage.removeItem(ea),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ea)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),c!=null&&c.clear&&Kr(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),p={},P.syncFromMetadata(),K==null||K.clear(),Y==null||Y.reset(),ke==null||ke.update()})})(),At&&At.addEventListener("submit",od),xe==null||xe.addEventListener("keydown",ad),xe==null||xe.addEventListener("input",sd),xe==null||xe.addEventListener("paste",ld);let vd=(yp=e.ownerDocument)!=null?yp:document;vd.addEventListener("keydown",id,!0);let wd="persona-attachment-drop-active",ua=0,Ll=()=>{ua=0,Te.classList.remove(wd)},Ms=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&St!==null},Cd=l=>{!al(l.dataTransfer)||!Ms()||(ua++,ua===1&&Te.classList.add(wd))},Ad=l=>{!al(l.dataTransfer)||!Ms()||(ua--,ua<=0&&Ll())},Sd=l=>{!al(l.dataTransfer)||!Ms()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Td=l=>{var h;if(!al(l.dataTransfer)||!Ms())return;l.preventDefault(),l.stopPropagation(),Ll();let m=Array.from((h=l.dataTransfer.files)!=null?h:[]);m.length!==0&&St.handleFiles(m)},wo=!0;Te.addEventListener("dragenter",Cd,wo),Te.addEventListener("dragleave",Ad,wo),e.addEventListener("dragover",Sd,wo),e.addEventListener("drop",Td,wo);let ei=e.ownerDocument,Ed=l=>{Ms()&&l.preventDefault()},Md=l=>{Ms()&&l.preventDefault()};ei.addEventListener("dragover",Ed),ei.addEventListener("drop",Md),ct.push(()=>{At&&At.removeEventListener("submit",od),xe==null||xe.removeEventListener("keydown",ad),xe==null||xe.removeEventListener("input",sd),xe==null||xe.removeEventListener("paste",ld),vd.removeEventListener("keydown",id,!0)}),ct.push(()=>{Te.removeEventListener("dragenter",Cd,wo),Te.removeEventListener("dragleave",Ad,wo),e.removeEventListener("dragover",Sd,wo),e.removeEventListener("drop",Td,wo),ei.removeEventListener("dragover",Ed),ei.removeEventListener("drop",Md),Ll()}),ct.push(()=>{$.cancel()}),Zt?ct.push(()=>{Zt==null||Zt.destroy()}):ln&&ct.push(()=>{ln==null||ln.remove()});let tn={update(l){var Un,Hr,mn,gn,nr,So,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu,qu,zu,Vu,Ku,Gu,Ju,Xu,Qu,Yu,Zu,em,tm,nm,rm,om,sm,am,im,lm,cm,dm,pm,um,mm,gm,fm,hm,ym,bm,xm,vm,wm,Cm,Am,Sm,Tm,Em,Mm,km,Lm,Pm;let m=r.toolCall,h=r.messageActions,x=(Un=r.layout)==null?void 0:Un.messages,C=r.colorScheme,k=r.loadingIndicator,j=r.iterationDisplay,O=(Hr=r.features)==null?void 0:Hr.showReasoning,N=(mn=r.features)==null?void 0:mn.showToolCalls,le=(gn=r.features)==null?void 0:gn.toolCallDisplay,se=(nr=r.features)==null?void 0:nr.reasoningDisplay,Z=(Sp=(So=r.features)==null?void 0:So.streamAnimation)==null?void 0:Sp.type;r={...r,...l},go(),Ho(e,r),Yi(e,r),Zi(e,r),Er(),r.colorScheme!==C&&ra();let we=ja.getForInstance(r.plugins);o.length=0,o.push(...we),H=(Ep=(Tp=r.launcher)==null?void 0:Tp.enabled)!=null?Ep:!0,W=(kp=(Mp=r.launcher)==null?void 0:Mp.autoExpand)!=null?kp:!1,Pe=(Pp=(Lp=r.features)==null?void 0:Lp.showReasoning)!=null?Pp:!0,Ie=(Rp=(Ip=r.features)==null?void 0:Ip.showToolCalls)!=null?Rp:!0,Se=(Hp=(Wp=r.features)==null?void 0:Wp.scrollToBottom)!=null?Hp:{};let Fe=Ft();oe=(Dp=(Bp=r.features)==null?void 0:Bp.scrollBehavior)!=null?Dp:{},Fe!==Ft()&&(sa(),bo()),io(),_n();let _e=re;if(re=(Op=(Np=r.features)==null?void 0:Np.showEventStreamToggle)!=null?Op:!1,re&&!_e){if(K||(ye=new _a(ie),K=new Fa(je,ye),Y=Y!=null?Y:new $a,ye.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),$.setSSEEventCallback((ne,Et)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,ne,Et),Y==null||Y.processEvent(ne,Et),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!bt&&Le){let ne=(_p=(Fp=r.features)==null?void 0:Fp.eventStream)==null?void 0:_p.classNames,Et="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=b("button",Et),bt.style.width="28px",bt.style.height="28px",bt.style.color=Pn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let qt=he("activity","18px","currentColor",1.5);qt&&bt.appendChild(qt);let it=Ke.clearChatButtonWrapper,Lt=Ke.closeButtonWrapper,dn=it||Lt;dn&&dn.parentNode===Le?Le.insertBefore(bt,dn):Le.appendChild(bt),bt.addEventListener("click",()=>{X?dr():$r()})}}else!re&&_e&&(dr(),bt&&(bt.remove(),bt=null),K==null||K.clear(),ye==null||ye.destroy(),K=null,ye=null,Y==null||Y.reset(),Y=null);if((($p=r.launcher)==null?void 0:$p.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((jp=r.launcher)==null?void 0:jp.enabled)===!1&&ln&&(ln.remove(),ln=null),((Up=r.launcher)==null?void 0:Up.enabled)!==!1&&!Zt&&!ln){let{instance:ne,element:Et}=cc({config:r,plugins:o,onToggle:dd});Zt=ne,ne||(ln=Et),e.appendChild(Et)}Zt&&Zt.update(r),me&&((qp=r.launcher)==null?void 0:qp.title)!==void 0&&(me.textContent=r.launcher.title),Ee&&((zp=r.launcher)==null?void 0:zp.subtitle)!==void 0&&(Ee.textContent=r.launcher.subtitle);let Ue=(Vp=r.layout)==null?void 0:Vp.header;if((Ue==null?void 0:Ue.layout)!==q&&Le){let ne=Ue?Ks(r,Ue,{showClose:F(),onClose:()=>$t(!1,"user")}):no({config:r,showClose:F(),onClose:()=>$t(!1,"user")});nt.replaceHeader(ne),Le=nt.header.element,M=nt.header.iconHolder,me=nt.header.headerTitle,Ee=nt.header.headerSubtitle,qe=nt.header.closeButton,q=Ue==null?void 0:Ue.layout}else if(Ue&&(M&&(M.style.display=Ue.showIcon===!1?"none":""),me&&(me.style.display=Ue.showTitle===!1?"none":""),Ee&&(Ee.style.display=Ue.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ue.showCloseButton===!1?"none":""),Ke.clearChatButtonWrapper)){let ne=Ue.showClearChat;if(ne!==void 0){Ke.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Et}=Ke;Et&&!Et.classList.contains("persona-absolute")&&(ne?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let mt=((Kp=r.layout)==null?void 0:Kp.showHeader)!==!1;Le&&(Le.style.display=mt?"":"none");let at=((Gp=r.layout)==null?void 0:Gp.showFooter)!==!1;Be&&(Be.style.display=at?"":"none"),Gn(),_n(),H!==B?H?$t(W,"auto"):(_=!0,da()):W!==T&&$t(W,"auto"),T=W,B=H,pa(),xd();let Ve=JSON.stringify(l.toolCall)!==JSON.stringify(m),Qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),xt=JSON.stringify((Jp=r.layout)==null?void 0:Jp.messages)!==JSON.stringify(x),R=((Xp=r.loadingIndicator)==null?void 0:Xp.render)!==(k==null?void 0:k.render)||((Qp=r.loadingIndicator)==null?void 0:Qp.renderIdle)!==(k==null?void 0:k.renderIdle)||((Yp=r.loadingIndicator)==null?void 0:Yp.showBubble)!==(k==null?void 0:k.showBubble),Ne=r.iterationDisplay!==j,He=((eu=(Zp=r.features)==null?void 0:Zp.showReasoning)!=null?eu:!0)!==(O!=null?O:!0)||((nu=(tu=r.features)==null?void 0:tu.showToolCalls)!=null?nu:!0)!==(N!=null?N:!0)||JSON.stringify((ru=r.features)==null?void 0:ru.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify((ou=r.features)==null?void 0:ou.reasoningDisplay)!==JSON.stringify(se);(Ve||Qe||xt||R||Ne||He)&&$&&(vs++,aa(et,$.getMessages(),te));let It=(au=(su=r.features)==null?void 0:su.streamAnimation)==null?void 0:au.type;if(It!==Z&&It&&It!=="none"){let ne=Vs(It,(lu=(iu=r.features)==null?void 0:iu.streamAnimation)==null?void 0:lu.plugins);ne&&Oi(ne,e)}let $e=(cu=r.launcher)!=null?cu:{},Jt=(du=$e.headerIconHidden)!=null?du:!1,Ct=(uu=(pu=r.layout)==null?void 0:pu.header)==null?void 0:uu.showIcon,cn=Jt||Ct===!1,Wn=$e.headerIconName,Dt=(mu=$e.headerIconSize)!=null?mu:"48px";if(M){let ne=Te.querySelector(".persona-border-b-persona-divider"),Et=ne==null?void 0:ne.querySelector(".persona-flex-col");if(cn)M.style.display="none",ne&&Et&&!ne.contains(Et)&&ne.insertBefore(Et,ne.firstChild);else{if(M.style.display="",M.style.height=Dt,M.style.width=Dt,ne&&Et&&(ne.contains(M)?M.nextSibling!==Et&&(M.remove(),ne.insertBefore(M,Et)):ne.insertBefore(M,Et)),Wn){let it=parseFloat(Dt)||24,Lt=he(Wn,it*.6,"currentColor",1);Lt?M.replaceChildren(Lt):M.textContent=(gu=$e.agentIconText)!=null?gu:"\u{1F4AC}"}else if($e.iconUrl){let it=M.querySelector("img");if(it)it.src=$e.iconUrl,it.style.height=Dt,it.style.width=Dt;else{let Lt=document.createElement("img");Lt.src=$e.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Dt,Lt.style.width=Dt,M.replaceChildren(Lt)}}else{let it=M.querySelector("svg"),Lt=M.querySelector("img");(it||Lt)&&M.replaceChildren(),M.textContent=(fu=$e.agentIconText)!=null?fu:"\u{1F4AC}"}let qt=M.querySelector("img");qt&&(qt.style.height=Dt,qt.style.width=Dt)}}let hn=(yu=(hu=r.layout)==null?void 0:hu.header)==null?void 0:yu.showTitle,$n=(xu=(bu=r.layout)==null?void 0:bu.header)==null?void 0:xu.showSubtitle;if(me&&(me.style.display=hn===!1?"none":""),Ee&&(Ee.style.display=$n===!1?"none":""),qe){((wu=(vu=r.layout)==null?void 0:vu.header)==null?void 0:wu.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let Et=(Cu=$e.closeButtonSize)!=null?Cu:"32px",qt=(Au=$e.closeButtonPlacement)!=null?Au:"inline";qe.style.height=Et,qe.style.width=Et;let{closeButtonWrapper:it}=Ke,Lt=qt==="top-right",dn=it==null?void 0:it.classList.contains("persona-absolute");if(it&&Lt!==dn)if(it.remove(),Lt)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Te.style.position="relative",Te.appendChild(it);else{let pt=(Tu=(Su=$e.clearChat)==null?void 0:Su.placement)!=null?Tu:"inline",pn=(Mu=(Eu=$e.clearChat)==null?void 0:Eu.enabled)!=null?Mu:!0;it.className=pn&&pt==="inline"?"":"persona-ml-auto";let Hn=Te.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(it)}if(qe.style.color=$e.closeButtonColor||Pn.actionIconColor,$e.closeButtonBackgroundColor?(qe.style.backgroundColor=$e.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),$e.closeButtonBorderWidth||$e.closeButtonBorderColor){let pt=$e.closeButtonBorderWidth||"0px",pn=$e.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${pn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");$e.closeButtonBorderRadius?(qe.style.borderRadius=$e.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),$e.closeButtonPaddingX?(qe.style.paddingLeft=$e.closeButtonPaddingX,qe.style.paddingRight=$e.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),$e.closeButtonPaddingY?(qe.style.paddingTop=$e.closeButtonPaddingY,qe.style.paddingBottom=$e.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let wn=(ku=$e.closeButtonIconName)!=null?ku:"x",gr=(Lu=$e.closeButtonIconText)!=null?Lu:"\xD7";qe.innerHTML="";let Ln=he(wn,"28px","currentColor",1);Ln?qe.appendChild(Ln):qe.textContent=gr;let Yt=(Pu=$e.closeButtonTooltipText)!=null?Pu:"Close chat",qn=(Iu=$e.closeButtonShowTooltip)!=null?Iu:!0;if(qe.setAttribute("aria-label",Yt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),qn&&Yt)){let pt=null,pn=()=>{if(pt||!qe)return;let ns=qe.ownerDocument,ma=ns.body;if(!ma)return;pt=Dr(ns,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let ga=Dr(ns,"div");ga.className="persona-clear-chat-tooltip-arrow",pt.appendChild(ga);let rs=qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Do),pt.style.left=`${rs.left+rs.width/2}px`,pt.style.top=`${rs.top-8}px`,pt.style.transform="translate(-50%, -100%)",ma.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",pn),it.addEventListener("mouseleave",Hn),qe.addEventListener("focus",pn),qe.addEventListener("blur",Hn),it._cleanupTooltip=()=>{Hn(),it&&(it.removeEventListener("mouseenter",pn),it.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",pn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Rt}=Ke;if(Je){let ne=(Ru=$e.clearChat)!=null?Ru:{},Et=(Wu=ne.enabled)!=null?Wu:!0,qt=(Bu=(Hu=r.layout)==null?void 0:Hu.header)==null?void 0:Bu.showClearChat,it=qt!==void 0?qt:Et,Lt=(Du=ne.placement)!=null?Du:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:dn}=Ke;!L()&&dn&&!dn.classList.contains("persona-absolute")&&(it?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let wn=Lt==="top-right",gr=Rt.classList.contains("persona-absolute");if(!L()&&wn!==gr&&it){if(Rt.remove(),wn)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",Te.style.position="relative",Te.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let Yt=Te.querySelector(".persona-border-b-persona-divider"),qn=Ke.closeButtonWrapper;Yt&&qn&&qn.parentElement===Yt?Yt.insertBefore(Rt,qn):Yt&&Yt.appendChild(Rt)}let Ln=Ke.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(wn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(it){if(!L()){let pt=(Nu=ne.size)!=null?Nu:"32px";Je.style.height=pt,Je.style.width=pt}let dn=(Ou=ne.iconName)!=null?Ou:"refresh-cw",wn=(Fu=ne.iconColor)!=null?Fu:"";Je.style.color=wn||Pn.actionIconColor,Je.innerHTML="";let gr=L()?"14px":"20px",Ln=he(dn,gr,"currentColor",2);if(Ln&&Je.appendChild(Ln),ne.backgroundColor?(Je.style.backgroundColor=ne.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let pt=ne.borderWidth||"0px",pn=ne.borderColor||"transparent";Je.style.border=`${pt} solid ${pn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");ne.borderRadius?(Je.style.borderRadius=ne.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),ne.paddingX?(Je.style.paddingLeft=ne.paddingX,Je.style.paddingRight=ne.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),ne.paddingY?(Je.style.paddingTop=ne.paddingY,Je.style.paddingBottom=ne.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Yt=(_u=ne.tooltipText)!=null?_u:"Clear chat",qn=($u=ne.showTooltip)!=null?$u:!0;if(Je.setAttribute("aria-label",Yt),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),qn&&Yt)){let pt=null,pn=()=>{if(pt||!Je)return;let ns=Je.ownerDocument,ma=ns.body;if(!ma)return;pt=Dr(ns,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let ga=Dr(ns,"div");ga.className="persona-clear-chat-tooltip-arrow",pt.appendChild(ga);let rs=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Do),pt.style.left=`${rs.left+rs.width/2}px`,pt.style.top=`${rs.top-8}px`,pt.style.transform="translate(-50%, -100%)",ma.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};Rt.addEventListener("mouseenter",pn),Rt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",pn),Je.addEventListener("blur",Hn),Rt._cleanupTooltip=()=>{Hn(),Rt&&(Rt.removeEventListener("mouseenter",pn),Rt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",pn),Je.removeEventListener("blur",Hn))}}}}let jn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ua],Xo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[hs.message,hs.messageAndClick];P=qa({parsers:jn,handlers:Xo,getSessionMetadata:y,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),te=Qf(r,P,pe),$.updateConfig(r),aa(et,$.getMessages(),te),xs(),Yc(),bl($.isStreaming());let Qo=((ju=r.voiceRecognition)==null?void 0:ju.enabled)===!0,Yo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Zo=((qu=(Uu=r.voiceRecognition)==null?void 0:Uu.provider)==null?void 0:qu.type)==="runtype";if(Qo&&(Yo||Zo))if(!D||!ve){let ne=ty(r.voiceRecognition,r.sendButton);ne&&(D=ne.micButton,ve=ne.micButtonWrapper,yt.insertBefore(ve,An),D.addEventListener("click",Za),D.disabled=$.isStreaming())}else{let ne=(zu=r.voiceRecognition)!=null?zu:{},Et=(Vu=r.sendButton)!=null?Vu:{},qt=(Ku=ne.iconName)!=null?Ku:"mic",it=(Gu=Et.size)!=null?Gu:"40px",Lt=(Ju=ne.iconSize)!=null?Ju:it,dn=parseFloat(Lt)||24;D.style.width=Lt,D.style.height=Lt,D.style.minWidth=Lt,D.style.minHeight=Lt;let wn=(Qu=(Xu=ne.iconColor)!=null?Xu:Et.textColor)!=null?Qu:"currentColor";D.innerHTML="";let gr=he(qt,dn,wn,2);gr?D.appendChild(gr):D.textContent="\u{1F3A4}";let Ln=(Yu=ne.backgroundColor)!=null?Yu:Et.backgroundColor;Ln?D.style.backgroundColor=Ln:D.style.backgroundColor="",wn?D.style.color=wn:D.style.color="var(--persona-text, #111827)",ne.borderWidth?(D.style.borderWidth=ne.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ne.borderColor?D.style.borderColor=ne.borderColor:D.style.borderColor="",ne.paddingX?(D.style.paddingLeft=ne.paddingX,D.style.paddingRight=ne.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ne.paddingY?(D.style.paddingTop=ne.paddingY,D.style.paddingBottom=ne.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Yt=ve==null?void 0:ve.querySelector(".persona-send-button-tooltip"),qn=(Zu=ne.tooltipText)!=null?Zu:"Start voice recognition";if(((em=ne.showTooltip)!=null?em:!1)&&qn)if(Yt)Yt.textContent=qn,Yt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=qn,ve==null||ve.insertBefore(pn,D)}else Yt&&(Yt.style.display="none");ve.style.display="",D.disabled=$.isStreaming()}else D&&ve&&(ve.style.display="none",((nm=(tm=r.voiceRecognition)==null?void 0:tm.provider)==null?void 0:nm.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Wr&&vo());if(((rm=r.attachments)==null?void 0:rm.enabled)===!0)if(!ht||!de){let ne=(om=r.attachments)!=null?om:{},qt=(am=((sm=r.sendButton)!=null?sm:{}).size)!=null?am:"40px";Pt||(Pt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pt.style.display="none",At.insertBefore(Pt,xe)),Xe||(Xe=document.createElement("input"),Xe.type="file",Xe.accept=((im=ne.allowedTypes)!=null?im:to).join(","),Xe.multiple=((lm=ne.maxFiles)!=null?lm:4)>1,Xe.style.display="none",Xe.setAttribute("aria-label","Attach files"),At.insertBefore(Xe,xe)),ht=b("div","persona-send-button-wrapper"),de=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),de.type="button",de.setAttribute("aria-label",(cm=ne.buttonTooltipText)!=null?cm:"Attach file");let it=(dm=ne.buttonIconName)!=null?dm:"paperclip",Lt=qt,dn=parseFloat(Lt)||40,wn=Math.round(dn*.6);de.style.width=Lt,de.style.height=Lt,de.style.minWidth=Lt,de.style.minHeight=Lt,de.style.fontSize="18px",de.style.lineHeight="1",de.style.backgroundColor="transparent",de.style.color="var(--persona-primary, #111827)",de.style.border="none",de.style.borderRadius="6px",de.style.transition="background-color 0.15s ease",de.addEventListener("mouseenter",()=>{de.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),de.addEventListener("mouseleave",()=>{de.style.backgroundColor="transparent"});let gr=he(it,wn,"currentColor",1.5);gr?de.appendChild(gr):de.textContent="\u{1F4CE}",de.addEventListener("click",qn=>{qn.preventDefault(),Xe==null||Xe.click()}),ht.appendChild(de);let Ln=(pm=ne.buttonTooltipText)!=null?pm:"Attach file",Yt=b("div","persona-send-button-tooltip");Yt.textContent=Ln,ht.appendChild(Yt),Ye.append(ht),!St&&Xe&&Pt&&(St=ds.fromConfig(ne),St.setPreviewsContainer(Pt),Xe.addEventListener("change",async()=>{St&&(Xe!=null&&Xe.files)&&(await St.handleFileSelect(Xe.files),Xe.value="")})),Te.querySelector(".persona-attachment-drop-overlay")||Te.appendChild(Yf(ne.dropOverlay))}else{ht.style.display="";let ne=(um=r.attachments)!=null?um:{};Xe&&(Xe.accept=((mm=ne.allowedTypes)!=null?mm:to).join(","),Xe.multiple=((gm=ne.maxFiles)!=null?gm:4)>1),St&&St.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else ht&&(ht.style.display="none"),St&&St.clearAttachments(),(fm=Te.querySelector(".persona-attachment-drop-overlay"))==null||fm.remove();let Xt=(hm=r.sendButton)!=null?hm:{},es=(ym=Xt.useIcon)!=null?ym:!1,Co=(bm=Xt.iconText)!=null?bm:"\u2191",Ao=Xt.iconName,Qr=(xm=Xt.tooltipText)!=null?xm:"Send message",ts=(vm=Xt.showTooltip)!=null?vm:!1,tt=(wm=Xt.size)!=null?wm:"40px",Ot=Xt.backgroundColor,Nt=Xt.textColor;if(es){if(ue.style.width=tt,ue.style.height=tt,ue.style.minWidth=tt,ue.style.minHeight=tt,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.innerHTML="",Nt?ue.style.color=Nt:ue.style.color="var(--persona-button-primary-fg, #ffffff)",Ao){let ne=parseFloat(tt)||24,Et=(Nt==null?void 0:Nt.trim())||"currentColor",qt=he(Ao,ne,Et,2);qt?ue.appendChild(qt):ue.textContent=Co}else ue.textContent=Co;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ot?(ue.style.backgroundColor=Ot,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=(Am=(Cm=r.copy)==null?void 0:Cm.sendButtonLabel)!=null?Am:"Send",ue.style.width="",ue.style.height="",ue.style.minWidth="",ue.style.minHeight="",ue.style.fontSize="",ue.style.lineHeight="",ue.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ot?(ue.style.backgroundColor=Ot,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),Nt?ue.style.color=Nt:ue.classList.add("persona-text-white");Xt.borderWidth?(ue.style.borderWidth=Xt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Xt.borderColor?ue.style.borderColor=Xt.borderColor:ue.style.borderColor="",Xt.paddingX?(ue.style.paddingLeft=Xt.paddingX,ue.style.paddingRight=Xt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Xt.paddingY?(ue.style.paddingTop=Xt.paddingY,ue.style.paddingBottom=Xt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Kt=An==null?void 0:An.querySelector(".persona-send-button-tooltip");if(ts&&Qr)if(Kt)Kt.textContent=Qr,Kt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Qr,An==null||An.insertBefore(ne,ue)}else Kt&&(Kt.style.display="none");let jt=(km=(Sm=r.layout)==null?void 0:Sm.contentMaxWidth)!=null?km:L()?(Mm=(Em=(Tm=r.launcher)==null?void 0:Tm.composerBar)==null?void 0:Em.contentMaxWidth)!=null?Mm:"720px":void 0;jt?(et.style.maxWidth=jt,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%",At&&(At.style.maxWidth=jt,At.style.marginLeft="auto",At.style.marginRight="auto"),zt&&(zt.style.maxWidth=jt,zt.style.marginLeft="auto",zt.style.marginRight="auto")):(et.style.maxWidth="",et.style.marginLeft="",et.style.marginRight="",et.style.width="",At&&(At.style.maxWidth="",At.style.marginLeft="",At.style.marginRight=""),zt&&(zt.style.maxWidth="",zt.style.marginLeft="",zt.style.marginRight=""));let gt=(Lm=r.statusIndicator)!=null?Lm:{},Ut=(Pm=gt.visible)!=null?Pm:!0;if(bn.style.display=Ut?"":"none",$){let ne=$.getStatus();Ht(bn,(qt=>{var it,Lt,dn,wn;return qt==="idle"?(it=gt.idleText)!=null?it:nn.idle:qt==="connecting"?(Lt=gt.connectingText)!=null?Lt:nn.connecting:qt==="connected"?(dn=gt.connectedText)!=null?dn:nn.connected:qt==="error"?(wn=gt.errorText)!=null?wn:nn.error:nn[qt]})(ne),gt,ne)}bn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let yn=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";bn.classList.add(yn)},open(){F()&&$t(!0,"api")},close(){F()&&$t(!1,"api")},toggle(){F()&&$t(!_,"api")},reconnect(){$.reconnectNow()},clearChat(){Sn=!1,$.clearMessages(),Lr.clear(),bo();try{localStorage.removeItem(ea),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ea)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),c!=null&&c.clear&&Kr(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),p={},P.syncFromMetadata(),K==null||K.clear(),Y==null||Y.reset(),ke==null||ke.update()},setMessage(l){return!xe||$.isStreaming()?!1:(!_&&F()&&$t(!0,"system"),xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let m=(l==null?void 0:l.trim())||xe.value.trim();return m?(!_&&F()&&$t(!0,"system"),xe.value="",xe.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return $.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!_&&F()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),ot("user"),$.isVoiceActive()&&Es()})),!0):Wr?!0:cd()?(!_&&F()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),Qa("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),ot("user"),Xr()}),!0):!1:Wr?(G.manuallyDeactivated=!0,dt(),vo("user"),!0):!1},injectMessage(l){return!_&&F()&&$t(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!_&&F()&&$t(!0,"system");let m=$.injectAssistantMessage(l);return ee&&(ee=!1,Me&&(clearTimeout(Me),Me=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(l){return!_&&F()&&$t(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!_&&F()&&$t(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!_&&F()&&$t(!0,"system"),$.injectMessageBatch(l)},injectComponentDirective(l){return!_&&F()&&$t(!0,"system"),$.injectComponentDirective(l)},injectTestMessage(l){!_&&F()&&$t(!0,"system"),$.injectTestEvent(l)},async connectStream(l,m){return $.connectStream(l,m)},__pushEventStreamEvent(l){K&&(Y==null||Y.processEvent(l.type,l.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!re||!K||$r()},hideEventStream(){X&&dr()},isEventStreamVisible(){return X},showArtifacts(){sr(r)&&(Sn=!1,Er(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){sr(r)&&(Sn=!0,Er())},upsertArtifact(l){return sr(r)?(Sn=!1,$.upsertArtifact(l)):null},selectArtifact(l){sr(r)&&$.selectArtifact(l)},clearArtifacts(){sr(r)&&$.clearArtifacts()},getArtifacts(){var l;return(l=$==null?void 0:$.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=$==null?void 0:$.getSelectedArtifactId())!=null?l:null},focusInput(){return H&&!_&&!L()||!xe?!1:(xe.focus(),!0)},async resolveApproval(l,m,h){let C=$.getMessages().find(k=>{var j;return k.variant==="approval"&&((j=k.approval)==null?void 0:j.id)===l});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${l}`);if(C.approval.toolType==="webmcp"){$.resolveWebMcpApproval(C.id,m);return}return $.resolveApproval(C.approval,m,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){v(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return F()&&_},isVoiceActive(){return G.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:F()&&_,launcherEnabled:H,voiceActive:G.active,streaming:$.isStreaming()}},showCSATFeedback(l){!_&&F()&&$t(!0,"system");let m=et.querySelector(".persona-feedback-container");m&&m.remove();let h=ol({onSubmit:async(x,C)=>{var k;$.isClientTokenMode()&&await $.submitCSATFeedback(x,C),(k=l==null?void 0:l.onSubmit)==null||k.call(l,x,C)},onDismiss:l==null?void 0:l.onDismiss,...l});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!_&&F()&&$t(!0,"system");let m=et.querySelector(".persona-feedback-container");m&&m.remove();let h=sl({onSubmit:async(x,C)=>{var k;$.isClientTokenMode()&&await $.submitNPSFeedback(x,C),(k=l==null?void 0:l.onSubmit)==null||k.call(l,x,C)},onDismiss:l==null?void 0:l.onDismiss,...l});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return $.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return $.submitNPSFeedback(l,m)},destroy(){Cl(),Jo!=null&&(clearInterval(Jo),Jo=null),ct.forEach(l=>l()),fe.remove(),lt==null||lt.remove(),Zt==null||Zt.destroy(),ln==null||ln.remove(),kr&&qe.removeEventListener("click",kr)}};if((((bp=n==null?void 0:n.debugTools)!=null?bp:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ct.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=O=>{let N=O.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),ct.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let O=le=>{let se=le.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&tn.showEventStream()},N=le=>{let se=le.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",N),ct.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",N)})}let h=O=>{let N=O.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.showArtifacts()},x=O=>{let N=O.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.hideArtifacts()},C=O=>{let N=O.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&tn.upsertArtifact(N.artifact)},k=O=>{let N=O.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&tn.selectArtifact(N.id)},j=O=>{let N=O.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",C),window.addEventListener("persona:selectArtifact",k),window.addEventListener("persona:clearArtifacts",j),ct.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",C),window.removeEventListener("persona:selectArtifact",k),window.removeEventListener("persona:clearArtifacts",j)})}let tr=nv(r.persistState);if(tr&&F()){let l=rv(tr.storage),m=`${tr.keyPrefix}widget-open`,h=`${tr.keyPrefix}widget-voice`,x=`${tr.keyPrefix}widget-voice-mode`;if(l){let C=((xp=tr.persist)==null?void 0:xp.openState)&&l.getItem(m)==="true",k=((vp=tr.persist)==null?void 0:vp.voiceState)&&l.getItem(h)==="true",j=((wp=tr.persist)==null?void 0:wp.voiceState)&&l.getItem(x)==="true";if(C&&setTimeout(()=>{tn.open(),setTimeout(()=>{var O;if(k||j)tn.startVoiceRecognition();else if((O=tr.persist)!=null&&O.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(Cp=tr.persist)!=null&&Cp.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(Ap=tr.persist)!=null&&Ap.voiceState&&(i.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),i.on("user:message",O=>{l.setItem(x,O.viaVoice?"true":"false")})),tr.clearOnChatClear){let O=()=>{l.removeItem(m),l.removeItem(h),l.removeItem(x)},N=()=>O();window.addEventListener("persona:clear-chat",N),ct.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return f&&F()&&setTimeout(()=>{tn.open()},0),As(),Ga||Om().then(()=>{$&&(vs++,Lr.clear(),aa(et,$.getMessages(),te))}).catch(()=>{}),tn};var ov=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},sv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},av=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},iv=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||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.")},Zf=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},kc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},eh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",kc(e)},Tc=e=>{e.style.transition=""},Ec=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Mc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ll=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lv=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},cv=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},th=(e,t,n,r,o,s,a)=>{var y,v,S,E,P,H;let i=Vn(s),d=i.reveal==="push";lv(e,t,n,r,d),cv(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?v:!0,u=(E=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?E:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ec(t),Tc(r),eh(r),Mc(n),ll(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((H=(P=s==null?void 0:s.launcher)==null?void 0:P.zIndex)!=null?H:Cn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),eh(r),sv(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ec(t),Tc(r),Mc(n),ll(o,r);let W=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":I;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=W,r.style.transform=T,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Tc(r),kc(r),ll(o,r);let W=ov(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),T=i.animate?"margin-left 180ms ease":"none",B=i.side==="right"?a?-W:0:a?0:-W;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+W}px`,t.style.transition=T,t.style.marginLeft=`${B}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ec(t),kc(r),Mc(n),ll(o,r);let W=i.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",T=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",B=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",av(r,i.maxHeight),r.style.overflow=W||B?"hidden":"visible",r.style.transition=T,W&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},dv=(e,t)=>{let n=e.ownerDocument.createElement("div");return Zf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Zf(n,r)},destroy(){n.remove()}}},pv=(e,t)=>{var H,W,I,T;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="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"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),u=(W=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)==null||W?(T=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?T:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},y=()=>{g(),Vn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{th(a,i,d,c,p,t,u)}),f.observe(a))},v=!1,S=()=>{th(a,i,d,c,p,t,u),y(),u&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,iv(a,Vn(t)))},E=a.ownerDocument.defaultView,P=()=>{S()};return E==null||E.addEventListener("resize",P),Vn(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),S(),{mode:"docked",host:p,shell:a,syncWidgetState(B){let q=B.launcherEnabled?B.open:!0;u!==q&&(u=q,S())},updateConfig(B){var q,U;t=B,((U=(q=t==null?void 0:t.launcher)==null?void 0:q.enabled)!=null?U:!0)===!1&&(u=!0),S()},destroy(){E==null||E.removeEventListener("resize",P),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Va=(e,t)=>rn(t)?pv(e,t):dv(e,t);var Lc={},uv=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},mv=()=>{try{if(typeof Lc!="undefined"&&Lc.url)return new URL("../widget.css",Lc.url).href}catch{}return null},nh=(e,t)=>{let n=mv(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Pc=e=>{var S;let t=uv(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Va(t,o),a,i=[],d=(E,P)=>{var T,B;let W=!((B=(T=P==null?void 0:P.launcher)==null?void 0:T.enabled)!=null?B:!0)||rn(P),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),W&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let q=E.attachShadow({mode:"open"});q.appendChild(I),nh(q,r)}else E.appendChild(I),nh(E,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},c=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let E=d(s.host,o);a=il(E,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),(S=e.onChatReady)==null||S.call(e);let g=E=>{f(),s.destroy(),s=Va(t,E),o=E,u()},y={update(E){var B,q,U,L,F,_;let P={...o,...E,launcher:{...(B=o==null?void 0:o.launcher)!=null?B:{},...(q=E==null?void 0:E.launcher)!=null?q:{},dock:{...(L=(U=o==null?void 0:o.launcher)==null?void 0:U.dock)!=null?L:{},...(_=(F=E==null?void 0:E.launcher)==null?void 0:F.dock)!=null?_:{}}}},H=rn(o),W=rn(P),I=Oo(o),T=Oo(P);if(H!==W||I!==T){g(P);return}o=P,s.updateConfig(o),a.update(E),c()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(y,{get(E,P,H){if(P==="host")return s.host;if(P in E)return Reflect.get(E,P,H);let W=a[P];return typeof W=="function"?W.bind(a):W}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var ih=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),gv=new Set(["button","a","input","select","textarea","details","summary"]),fv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ic=/\b(product|card|item|listing|result)\b/i,Wc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,hv=3e3,yv=100;function lh(e){let t=typeof e.className=="string"?e.className:"";if(Ic.test(t)||e.id&&Ic.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ic.test(r.value))return!0}return!1}function ch(e){var t;return Wc.test(((t=e.textContent)!=null?t:"").trim())}function dh(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function bv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function rh(e){let t=e.match(Wc);return t?t[0]:null}function oh(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function xv(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var vv="commerce-card",wv="result-card";function sh(e){return!lh(e)||!ch(e)||!dh(e)&&!bv(e)?0:5200}function ah(e){var r;return!lh(e)||ch(e)||!dh(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hc=[{id:vv,scoreElement(e){return sh(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Wc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(sh(e)===0)return null;let{title:n,href:r}=oh(e),o=(p=(c=rh(((d=e.textContent)!=null?d:"").trim()))!=null?c:rh(t.text))!=null?p:"",s=xv(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
+ `)}},{id:wv,scoreElement(e){return ah(e)},formatSummary(e,t){if(ah(e)===0)return null;let{title:n,href:r}=oh(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
+ `)}}];function Cv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Av(e){var p,u,f,g,y,v,S,E,P,H,W,I,T;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(y=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?y:".persona-host",o=(S=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?S:200,s=(P=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?P:!0,a=(H=t.root)!=null?H:e.root,i=(W=t.mode)!=null?W:"structured",d=(I=t.maxCandidates)!=null?I:Math.max(500,n*10),c=(T=e.rules)!=null?T:Hc;return i==="simple"&&e.rules&&e.rules.length>0?(Cv(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function Rc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Sv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Tv(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"||gv.has(t)||n&&fv.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ph(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 Ev(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);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 d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Bc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Rc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Sv){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Rc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>Rc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Mv(e){return e==="static"?yv:hv}function uh(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:Bc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Tv(e),attributes:Ev(e)}}function kv(e,t,n,r){let o=Mv(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Lv(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function Pv(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(ih.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ph(c)){i=a.nextNode();continue}let u=uh(c,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(S=>S==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:y,formattingRule:v}=kv(c,u,e.rules,n);o.push({el:c,domIndex:s,enriched:u,score:y,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;Lv(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function Iv(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(ih.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!ph(d)){s=o.nextNode();continue}let p=uh(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function mh(e={}){var r;let t=Av(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Iv(t,n):Pv(t,n):[]}var cl=100;function gh(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
114
114
  ${a.map(i=>`- ${i.split(`
115
115
  `).join(`
116
116
  `)}`).join(`
117
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,sl)}" (clickable)`);r.push(`Interactive elements:
117
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,cl)}" (clickable)`);r.push(`Interactive elements:
118
118
  ${a.join(`
119
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,sl)}" (navigable)`);r.push(`Navigation links:
119
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,cl)}" (navigable)`);r.push(`Navigation links:
120
120
  ${a.join(`
121
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,sl)}" (input)`);r.push(`Form inputs:
121
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,cl)}" (input)`);r.push(`Form inputs:
122
122
  ${a.join(`
123
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,sl)}"`);r.push(`Content:
123
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,cl)}"`);r.push(`Content:
124
124
  ${a.join(`
125
125
  `)}`)}return r.join(`
126
126
 
127
- `)}function rh(){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 oh(){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 sh(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Or(e.colors.primary,.95),100:Or(e.colors.primary,.9),200:Or(e.colors.primary,.8),300:Or(e.colors.primary,.7),400:Or(e.colors.primary,.6),500:e.colors.primary,600:Or(e.colors.primary,.8),700:Or(e.colors.primary,.7),800:Or(e.colors.primary,.6),900:Or(e.colors.primary,.5),950:Or(e.colors.primary,.45)}}),{...t,palette:n}}}}function ah(){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 ih(){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 Or(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function lh(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var yv={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"}}},ch={components:{panel:{borderRadius:"0",shadow:"none"}}},kc={id:"shop",label:"Shopping Assistant",config:{theme:yv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:zn},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?"]}},Lc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ch}},Pc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ch}},Ic={shop:kc,minimal:Lc,fullscreen:Pc};function dh(e){return Ic[e]}var ph=Cc;function to(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function bv(e){if(e)return{getHeaders:to(e.getHeaders),onFeedback:to(e.onFeedback),onCopy:to(e.onCopy),requestMiddleware:to(e.requestMiddleware),actionHandlers:to(e.actionHandlers),actionParsers:to(e.actionParsers),postprocessMessage:to(e.postprocessMessage),contextProviders:to(e.contextProviders),streamParser:to(e.streamParser)}}var uh=`({ text, message }: any) => {
127
+ `)}function fh(){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 hh(){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 yh(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Or(e.colors.primary,.95),100:Or(e.colors.primary,.9),200:Or(e.colors.primary,.8),300:Or(e.colors.primary,.7),400:Or(e.colors.primary,.6),500:e.colors.primary,600:Or(e.colors.primary,.8),700:Or(e.colors.primary,.7),800:Or(e.colors.primary,.6),900:Or(e.colors.primary,.5),950:Or(e.colors.primary,.45)}}),{...t,palette:n}}}}function bh(){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 xh(){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 Or(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function vh(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Rv={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"}}},wh={components:{panel:{borderRadius:"0",shadow:"none"}}},Dc={id:"shop",label:"Shopping Assistant",config:{theme:Rv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:zn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Nc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:wh}},Oc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:wh}},Fc={shop:Dc,minimal:Nc,fullscreen:Oc};function Ch(e){return Fc[e]}var Ah=Pc;function oo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Wv(e){if(e)return{getHeaders:oo(e.getHeaders),onFeedback:oo(e.onFeedback),onCopy:oo(e.onCopy),requestMiddleware:oo(e.requestMiddleware),actionHandlers:oo(e.actionHandlers),actionParsers:oo(e.actionParsers),postprocessMessage:oo(e.postprocessMessage),contextProviders:oo(e.contextProviders),streamParser:oo(e.streamParser)}}var Sh=`({ text, message }: any) => {
128
128
  const jsonSource = (message as any).rawContent || text || message.content;
129
129
  if (!jsonSource || typeof jsonSource !== 'string') return null;
130
130
  let cleanJson = jsonSource
@@ -137,7 +137,7 @@ ${a.join(`
137
137
  if (parsed.action) return { type: parsed.action, payload: parsed };
138
138
  } catch (e) { return null; }
139
139
  return null;
140
- }`,mh=`function(ctx) {
140
+ }`,Th=`function(ctx) {
141
141
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
142
142
  if (!jsonSource || typeof jsonSource !== 'string') return null;
143
143
  var cleanJson = jsonSource
@@ -150,7 +150,7 @@ ${a.join(`
150
150
  if (parsed.action) return { type: parsed.action, payload: parsed };
151
151
  } catch (e) { return null; }
152
152
  return null;
153
- }`,gh=`(action: any, context: any) => {
153
+ }`,Eh=`(action: any, context: any) => {
154
154
  if (action.type !== 'nav_then_click') return;
155
155
  const payload = action.payload || action.raw || {};
156
156
  const url = payload?.page;
@@ -167,7 +167,7 @@ ${a.join(`
167
167
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
168
168
  window.location.href = targetUrl;
169
169
  return { handled: true, displayText: text };
170
- }`,fh=`function(action, context) {
170
+ }`,Mh=`function(action, context) {
171
171
  if (action.type !== 'nav_then_click') return;
172
172
  var payload = action.payload || action.raw || {};
173
173
  var url = payload.page;
@@ -184,26 +184,26 @@ ${a.join(`
184
184
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
185
185
  window.location.href = targetUrl;
186
186
  return { handled: true, displayText: text };
187
- }`,xv=`(parsed: any) => {
187
+ }`,Hv=`(parsed: any) => {
188
188
  if (!parsed || typeof parsed !== 'object') return null;
189
189
  if (parsed.action === 'nav_then_click') return 'Navigating...';
190
190
  if (parsed.action === 'message') return parsed.text || '';
191
191
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
192
192
  return parsed.text || null;
193
- }`,vv=`function(parsed) {
193
+ }`,Bv=`function(parsed) {
194
194
  if (!parsed || typeof parsed !== 'object') return null;
195
195
  if (parsed.action === 'nav_then_click') return 'Navigating...';
196
196
  if (parsed.action === 'message') return parsed.text || '';
197
197
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
198
198
  return parsed.text || null;
199
- }`;function wv(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 al(e){var t,n;return(n=(t=e.parserType)!=null?t:wv(e.streamParser))!=null?n:"plain"}function il(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function ll(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function cl(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(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} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function dl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(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} },`)),o&&(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,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Rc(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 hh(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),hh(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function Oo(e,t,n,r){n&&(e.push(`${r}${t}: {`),hh(e,n,`${r} `),e.push(`${r}},`))}function Ua(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function yh(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:bv(n.hooks)}:void 0;return t==="esm"?Cv(r,o):t==="script-installer"?Tv(r,o):t==="script-advanced"?Mv(r,o):t==="react-component"?Av(r,o):t==="react-advanced"?Sv(r,o):Ev(r,o)}function Cv(e,t){let n=t==null?void 0:t.hooks,r=al(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ua(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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Oo(s,"theme",e.theme," "),e.launcher&&Oo(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(...il(e," ")),s.push(...ll(e," ",n)),s.push(...cl(e," ")),s.push(...dl(e," ")),s.push(...Rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
- `)}function Av(e,t){let n=t==null?void 0:t.hooks,r=al(e),o=r!=="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: '${Ua(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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Oo(s,"theme",e.theme," "),e.launcher&&Oo(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(...il(e," ")),s.push(...ll(e," ",n)),s.push(...cl(e," ")),s.push(...dl(e," ")),s.push(...Rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&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(`
201
- `)}function Sv(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ua(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}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Oo(r,"theme",e.theme," "),e.launcher&&Oo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),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(...il(e," ")),r.push(...ll(e," ",n)),r.push(...cl(e," ")),r.push(...dl(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${xv}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${uh}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${uh}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${gh}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${gh}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
- `)}function bh(e){var o;let t=al(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.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&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function Tv(e,t){let n=bh(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/install.global.js" data-config='${s}'></script>`}function Ev(e,t){let n=t==null?void 0:t.hooks,r=al(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ua(t)}',`,...t!=null&&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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Oo(s,"theme",e.theme," "),e.launcher&&Oo(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(...il(e," ")),s.push(...ll(e," ",n)),s.push(...cl(e," ")),s.push(...dl(e," ")),s.push(...Rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
- `)}function Mv(e,t){let n=t==null?void 0:t.hooks,r=bh(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
199
+ }`;function Dv(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 dl(e){var t,n;return(n=(t=e.parserType)!=null?t:Dv(e.streamParser))!=null?n:"plain"}function pl(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function ul(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function ml(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(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} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function gl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(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} },`)),o&&(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,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function _c(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function kh(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),kh(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function _o(e,t,n,r){n&&(e.push(`${r}${t}: {`),kh(e,n,`${r} `),e.push(`${r}},`))}function Ka(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Lh(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:Wv(n.hooks)}:void 0;return t==="esm"?Nv(r,o):t==="script-installer"?_v(r,o):t==="script-advanced"?jv(r,o):t==="react-component"?Ov(r,o):t==="react-advanced"?Fv(r,o):$v(r,o)}function Nv(e,t){let n=t==null?void 0:t.hooks,r=dl(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ka(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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&_o(s,"theme",e.theme," "),e.launcher&&_o(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(...pl(e," ")),s.push(...ul(e," ",n)),s.push(...ml(e," ")),s.push(...gl(e," ")),s.push(..._c(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
+ `)}function Ov(e,t){let n=t==null?void 0:t.hooks,r=dl(e),o=r!=="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: '${Ka(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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&_o(s,"theme",e.theme," "),e.launcher&&_o(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(...pl(e," ")),s.push(...ul(e," ",n)),s.push(...ml(e," ")),s.push(...gl(e," ")),s.push(..._c(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&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(`
201
+ `)}function Fv(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ka(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}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&_o(r,"theme",e.theme," "),e.launcher&&_o(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),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(...pl(e," ")),r.push(...ul(e," ",n)),r.push(...ml(e," ")),r.push(...gl(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Hv}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Sh}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Sh}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Eh}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Eh}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
+ `)}function Ph(e){var o;let t=dl(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.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&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function _v(e,t){let n=Ph(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/install.global.js" data-config='${s}'></script>`}function $v(e,t){let n=t==null?void 0:t.hooks,r=dl(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ka(t)}',`,...t!=null&&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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&_o(s,"theme",e.theme," "),e.launcher&&_o(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(...pl(e," ")),s.push(...ul(e," ",n)),s.push(...ml(e," ")),s.push(...gl(e," ")),s.push(..._c(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
+ `)}function jv(e,t){let n=t==null?void 0:t.hooks,r=Ph(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
204
204
  `).map((a,i)=>i===0?a:" "+a).join(`
205
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&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(${vv});`),s.push(" };")),s.push(""),n!=null&&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(` ${mh}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${mh}`),s.push(" ];")),s.push(""),n!=null&&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(` ${fh}`),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(` ${fh}`),s.push(" ];")),s.push(""),n!=null&&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!=null&&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!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&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: '${Ua(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
- `)}var xh={desktop:{w:1280,h:800},mobile:{w:390,h:844}},vh=.1,wh=.15,Ch=1.5,Wc=24,Ah=40,kv=`
205
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&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(${Bv});`),s.push(" };")),s.push(""),n!=null&&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(` ${Th}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Th}`),s.push(" ];")),s.push(""),n!=null&&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(` ${Mh}`),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(` ${Mh}`),s.push(" ];")),s.push(""),n!=null&&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!=null&&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!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&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: '${Ka(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
+ `)}var Ih={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Rh=.1,Wh=.15,Hh=1.5,$c=24,Bh=40,Uv=`
207
207
  /* \u2500\u2500 Root \u2500\u2500 */
208
208
  .persona-dc-root {
209
209
  display: flex;
@@ -354,7 +354,7 @@ ${a.join(`
354
354
  .persona-dc-stage {
355
355
  height: 550px;
356
356
  min-height: 400px;
357
- padding: ${Wc}px;
357
+ padding: ${$c}px;
358
358
  overflow: auto;
359
359
  background: #f0f1f3;
360
360
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -444,5 +444,5 @@ ${a.join(`
444
444
  min-height: 300px;
445
445
  }
446
446
  }
447
- `;function Lv(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=kv,document.head.appendChild(e)}function Pv(e,t){let n=e.clientWidth-Wc*2-Ah,r=e.clientHeight-Wc*2-Ah;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Iv(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function Sh(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Lv();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,b=1,v=!1,T=y("div","persona-dc-root"),E=y("div","persona-dc-toolbar"),P=y("div","persona-dc-toolbar-lead"),I=y("div","persona-dc-toolbar-trail"),M=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Y(-1)}),L=y("div");L.style.position="relative";let C=y("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let R=y("span","persona-dc-title-text"),U=y("span","persona-dc-title-chevron"),j=he("chevron-down",12,"currentColor",2);j&&U.appendChild(j),C.append(R,U);let W=y("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let O=!1;function F(){W.innerHTML="";for(let be=0;be<n.length;be++){let Ge=n[be],ft=y("button","persona-dc-dropdown-item");ft.type="button",ft.setAttribute("role","option"),ft.setAttribute("aria-current",be===p?"true":"false");let Ht=y("span");if(Ht.textContent=Ge.title,ft.appendChild(Ht),Ge.description){let nt=y("span","persona-dc-dropdown-desc");nt.textContent=Ge.description,ft.appendChild(nt)}ft.addEventListener("click",()=>{Me(),ke(be)}),W.appendChild(ft)}}function ee(){O=!O,W.style.display=O?"":"none",C.setAttribute("aria-expanded",O?"true":"false"),O&&F()}function Me(){O&&(O=!1,W.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",be=>{be.stopPropagation(),ee()});let pe=()=>Me();document.addEventListener("click",pe),L.append(C,W);let te=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Y(1)}),Pe=y("span","persona-dc-counter");P.append(M,L,te,Pe);let Ie=null;i&&(Ie=Ba({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:be=>{u=be,ie.dataset.device=u,g=null,X()}}),I.appendChild(Ie.element));let re=null;if(a){let be=y("div","persona-dc-zoom-controls"),Ge=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let nt=g!=null?g:b;g=Math.max(wh,nt-vh),X()}});re=y("span","persona-dc-zoom-level"),re.title="Reset to 100%",re.style.cursor="pointer",re.addEventListener("click",()=>{g=1,X()});let ft=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let nt=g!=null?g:b;g=Math.min(Ch,nt+vh),X()}}),Ht=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,X()}});be.append(Ge,re,ft,Ht),I.appendChild(be)}if(d){let be=y("div","persona-dc-separator");I.appendChild(be);let Ge=Ba({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ft=>{f=ft,ie.dataset.colorScheme=f,je()}});I.appendChild(Ge.element)}let Se=y("div","persona-dc-separator");I.appendChild(Se);let oe=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});I.appendChild(oe),E.append(P,I);let ae=y("div","persona-dc-stage"),ie=y("div","persona-dc-iframe-wrapper");ie.dataset.device=u,ie.dataset.colorScheme=f;let ye=y("iframe","persona-dc-iframe");ye.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ye.setAttribute("loading","lazy"),ye.title=n[p].title,ie.appendChild(ye),ae.appendChild(ie),T.append(E,ae),e.appendChild(T);function je(){var be;try{let Ge=(be=ye.contentDocument)==null?void 0:be.body;if(!Ge)return;f==="dark"?Ge.classList.add("theme-dark"):Ge.classList.remove("theme-dark")}catch{}}ye.addEventListener("load",()=>je());function K(){let be=n[p];R.textContent=be.title,Pe.textContent=`${p+1} / ${n.length}`,ye.title=be.title}function Y(be){let Ge=((p+be)%n.length+n.length)%n.length;ke(Ge)}function ke(be){be<0||be>=n.length||(p=be,ye.src=n[p].url,K(),c==null||c(p,n[p]))}function X(){var ft;if(v)return;let be=(ft=xh[u])!=null?ft:xh.desktop;b=Pv(ae,be);let Ge=Math.max(wh,Math.min(Ch,g!=null?g:b));Iv(ie,ye,be,Ge,u),re&&(re.textContent=`${Math.round(Ge*100)}%`)}let ce=new ResizeObserver(()=>X());ce.observe(ae),K(),ye.src=n[p].url,requestAnimationFrame(()=>X());function Re(){v||(v=!0,ce.disconnect(),document.removeEventListener("click",pe),T.remove())}return{element:T,goTo:ke,next:()=>Y(1),prev:()=>Y(-1),getIndex:()=>p,setDevice(be){u=be,ie.dataset.device=be,Ie==null||Ie.setSelected(be),g=null,X()},setColorScheme(be){f=be,ie.dataset.colorScheme=be},setZoom(be){g=be,X()},destroy:Re}}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,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,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,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,parseSuggestRepliesPayload,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
447
+ `;function qv(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Uv,document.head.appendChild(e)}function zv(e,t){let n=e.clientWidth-$c*2-Bh,r=e.clientHeight-$c*2-Bh;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Vv(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function Dh(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");qv();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,y=1,v=!1,S=b("div","persona-dc-root"),E=b("div","persona-dc-toolbar"),P=b("div","persona-dc-toolbar-lead"),H=b("div","persona-dc-toolbar-trail"),W=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Y(-1)}),I=b("div");I.style.position="relative";let T=b("button","persona-dc-title-btn");T.type="button",T.setAttribute("aria-expanded","false"),T.setAttribute("aria-haspopup","listbox");let B=b("span","persona-dc-title-text"),q=b("span","persona-dc-title-chevron"),U=he("chevron-down",12,"currentColor",2);U&&q.appendChild(U),T.append(B,q);let L=b("div","persona-dc-dropdown");L.setAttribute("role","listbox"),L.style.display="none";let F=!1;function _(){L.innerHTML="";for(let be=0;be<n.length;be++){let Ge=n[be],ft=b("button","persona-dc-dropdown-item");ft.type="button",ft.setAttribute("role","option"),ft.setAttribute("aria-current",be===p?"true":"false");let Ht=b("span");if(Ht.textContent=Ge.title,ft.appendChild(Ht),Ge.description){let nt=b("span","persona-dc-dropdown-desc");nt.textContent=Ge.description,ft.appendChild(nt)}ft.addEventListener("click",()=>{Me(),ke(be)}),L.appendChild(ft)}}function ee(){F=!F,L.style.display=F?"":"none",T.setAttribute("aria-expanded",F?"true":"false"),F&&_()}function Me(){F&&(F=!1,L.style.display="none",T.setAttribute("aria-expanded","false"))}T.addEventListener("click",be=>{be.stopPropagation(),ee()});let pe=()=>Me();document.addEventListener("click",pe),I.append(T,L);let te=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Y(1)}),Pe=b("span","persona-dc-counter");P.append(W,I,te,Pe);let Ie=null;i&&(Ie=Oa({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:be=>{u=be,ie.dataset.device=u,g=null,X()}}),H.appendChild(Ie.element));let re=null;if(a){let be=b("div","persona-dc-zoom-controls"),Ge=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let nt=g!=null?g:y;g=Math.max(Wh,nt-Rh),X()}});re=b("span","persona-dc-zoom-level"),re.title="Reset to 100%",re.style.cursor="pointer",re.addEventListener("click",()=>{g=1,X()});let ft=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let nt=g!=null?g:y;g=Math.min(Hh,nt+Rh),X()}}),Ht=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,X()}});be.append(Ge,re,ft,Ht),H.appendChild(be)}if(d){let be=b("div","persona-dc-separator");H.appendChild(be);let Ge=Oa({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ft=>{f=ft,ie.dataset.colorScheme=f,je()}});H.appendChild(Ge.element)}let Se=b("div","persona-dc-separator");H.appendChild(Se);let oe=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});H.appendChild(oe),E.append(P,H);let ae=b("div","persona-dc-stage"),ie=b("div","persona-dc-iframe-wrapper");ie.dataset.device=u,ie.dataset.colorScheme=f;let ye=b("iframe","persona-dc-iframe");ye.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ye.setAttribute("loading","lazy"),ye.title=n[p].title,ie.appendChild(ye),ae.appendChild(ie),S.append(E,ae),e.appendChild(S);function je(){var be;try{let Ge=(be=ye.contentDocument)==null?void 0:be.body;if(!Ge)return;f==="dark"?Ge.classList.add("theme-dark"):Ge.classList.remove("theme-dark")}catch{}}ye.addEventListener("load",()=>je());function K(){let be=n[p];B.textContent=be.title,Pe.textContent=`${p+1} / ${n.length}`,ye.title=be.title}function Y(be){let Ge=((p+be)%n.length+n.length)%n.length;ke(Ge)}function ke(be){be<0||be>=n.length||(p=be,ye.src=n[p].url,K(),c==null||c(p,n[p]))}function X(){var ft;if(v)return;let be=(ft=Ih[u])!=null?ft:Ih.desktop;y=zv(ae,be);let Ge=Math.max(Wh,Math.min(Hh,g!=null?g:y));Vv(ie,ye,be,Ge,u),re&&(re.textContent=`${Math.round(Ge*100)}%`)}let ce=new ResizeObserver(()=>X());ce.observe(ae),K(),ye.src=n[p].url,requestAnimationFrame(()=>X());function Re(){v||(v=!0,ce.disconnect(),document.removeEventListener("click",pe),S.remove())}return{element:S,goTo:ke,next:()=>Y(1),prev:()=>Y(-1),getIndex:()=>p,setDevice(be){u=be,ie.dataset.device=be,Ie==null||Ie.setSelected(be),g=null,X()},setColorScheme(be){f=be,ie.dataset.colorScheme=be},setZoom(be){g=be,X()},destroy:Re}}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,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,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,markdownPostprocessor,mergeWithDefaults,normalizeContent,parseAskUserQuestionPayload,parseSuggestRepliesPayload,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
448
448
  //# sourceMappingURL=index.cjs.map