@runtypelabs/persona 4.4.0 → 4.4.1
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/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +27 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +25 -25
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +29 -29
- package/dist/index.js.map +1 -1
- package/dist/theme-editor-preview.cjs +28 -28
- package/dist/theme-editor-preview.js +26 -26
- package/dist/widget.css +24 -0
- package/package.json +1 -1
- package/src/components/event-stream-view.test.ts +23 -22
- package/src/components/event-stream-view.ts +25 -47
- package/src/styles/widget.css +24 -0
- package/src/ui.ts +9 -0
package/dist/index.cjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
"use strict";var yh=Object.create;var za=Object.defineProperty;var bh=Object.getOwnPropertyDescriptor;var xh=Object.getOwnPropertyNames;var vh=Object.getPrototypeOf,wh=Object.prototype.hasOwnProperty;var ta=(e,t)=>()=>(e&&(t=e(e=0)),t);var ml=(e,t)=>{for(var n in t)za(e,n,{get:t[n],enumerable:!0})},Gu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xh(t))!wh.call(e,o)&&o!==n&&za(e,o,{get:()=>t[o],enumerable:!(r=bh(t,o))||r.enumerable});return e};var gl=(e,t,n)=>(n=e!=null?yh(vh(e)):{},Gu(t||!e||!e.__esModule?za(n,"default",{value:e,enumerable:!0}):n,e)),Ch=e=>Gu(za({},"__esModule",{value:!0}),e);var Qu={};ml(Qu,{DOMPurify:()=>Xu.default,Marked:()=>Ju.Marked});var Ju,Xu,Yu=ta(()=>{"use strict";Ju=require("marked"),Xu=gl(require("dompurify"),1)});var Ls,Pl=ta(()=>{"use strict";Ls=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 Sy(e){return e.replace(/\/+$/,"")}async function Ty(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 pi,Ym=ta(()=>{"use strict";Pl();pi=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 Ls(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 g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let l=`${Sy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(l,{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 Ty(p));let u=p.body.getReader();for(;;){let{done:g,value:f}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let l=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,l),(i=r.onError)==null||i.call(r,l)}}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 ui,Zm=ta(()=>{"use strict";ui=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 eg={};ml(eg,{FallbackSpeechEngine:()=>ui,RuntypeSpeechEngine:()=>pi});var tg=ta(()=>{"use strict";Ym();Zm()});var ev={};ml(ev,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Ml,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>El,ASK_USER_QUESTION_TOOL_NAME:()=>aa,AgentWidgetClient:()=>Jo,AgentWidgetSession:()=>Is,AttachmentManager:()=>Zo,BrowserSpeechEngine:()=>So,DEFAULT_COMPONENTS:()=>Bl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>gi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Xn,DEFAULT_PALETTE:()=>Wl,DEFAULT_SEMANTIC:()=>Hl,DEFAULT_WIDGET_CONFIG:()=>Bt,PRESETS:()=>Ac,PRESET_FULLSCREEN:()=>Cc,PRESET_MINIMAL:()=>wc,PRESET_SHOP:()=>vc,ReadAloudController:()=>Yo,SUGGEST_REPLIES_CLIENT_TOOL:()=>Qa,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Al,SUGGEST_REPLIES_TOOL_NAME:()=>xr,THEME_ZONES:()=>cg,VERSION:()=>lr,WEBMCP_TOOL_PREFIX:()=>br,WebMcpBridge:()=>Ss,accessibilityPlugin:()=>If,animationsPlugin:()=>Rf,applyThemeVariables:()=>To,attachHeaderToContainer:()=>ts,brandPlugin:()=>Wf,buildComposer:()=>Ds,buildDefaultHeader:()=>Ul,buildHeader:()=>eo,buildHeaderWithLayout:()=>Bs,buildMinimalHeader:()=>ql,builtInClientToolsForDispatch:()=>ca,collectEnrichedPageContext:()=>Lf,componentRegistry:()=>to,createActionManager:()=>Wa,createAgentExperience:()=>Xi,createAskUserQuestionBubble:()=>Im,createBestAvailableVoiceProvider:()=>di,createBubbleWithLayout:()=>Bg,createCSATFeedback:()=>Ki,createComboButton:()=>Li,createComponentMiddleware:()=>df,createComponentStreamParser:()=>Ui,createDefaultSanitizer:()=>hl,createDemoCarousel:()=>Yf,createDirectivePostprocessor:()=>im,createDropdownMenu:()=>Lo,createFlexibleJsonStreamParser:()=>Bm,createIconButton:()=>Gt,createImagePart:()=>Um,createJsonStreamParser:()=>si,createLabelButton:()=>Ea,createLocalStorageAdapter:()=>ji,createMarkdownProcessor:()=>na,createMarkdownProcessorFromConfig:()=>Ko,createMessageActions:()=>Ql,createNPSFeedback:()=>Gi,createPlainTextParser:()=>ri,createPlugin:()=>Df,createRegexJsonParser:()=>oi,createStandardBubble:()=>Ns,createTextPart:()=>ma,createTheme:()=>Ws,createThemeObserver:()=>bi,createToggleGroup:()=>Ma,createTypingIndicator:()=>ns,createVoiceProvider:()=>Ao,createWidgetHostLayout:()=>Ha,createXmlParser:()=>ai,default:()=>Ff,defaultActionHandlers:()=>as,defaultJsonActionParser:()=>Ra,defaultParseRules:()=>bc,detectColorScheme:()=>ba,directivePostprocessor:()=>lm,ensureAskUserQuestionSheet:()=>Ms,escapeHtml:()=>Br,extractComponentDirectiveFromMessage:()=>Vi,fileToImagePart:()=>qm,formatEnrichedContext:()=>Pf,generateAssistantMessageId:()=>Xo,generateCodeSnippet:()=>zf,generateMessageId:()=>Om,generateStableSelector:()=>xc,generateUserMessageId:()=>ks,getActiveTheme:()=>Hs,getColorScheme:()=>Nl,getDisplayText:()=>_m,getHeaderLayout:()=>zl,getImageParts:()=>jm,getPreset:()=>Of,hasComponentDirective:()=>zi,hasImages:()=>$m,headerLayouts:()=>Pi,highContrastPlugin:()=>Bf,initAgentWidget:()=>gc,isAskUserQuestionMessage:()=>Jr,isComponentDirectiveType:()=>cf,isDockedMountMode:()=>on,isSuggestRepliesMessage:()=>la,isVoiceSupported:()=>fa,isWebMcpToolName:()=>yo,latestAgentSuggestions:()=>Ya,listRegisteredStreamAnimations:()=>Eg,markdownPostprocessor:()=>fl,mergeWithDefaults:()=>fi,normalizeContent:()=>Fm,parseAskUserQuestionPayload:()=>Xr,parseSuggestRepliesPayload:()=>Tl,pickBestVoice:()=>Ps,pluginRegistry:()=>Ia,reducedMotionPlugin:()=>Hf,registerStreamAnimationPlugin:()=>Sg,removeAskUserQuestionSheet:()=>vo,renderComponentDirective:()=>qi,renderLoadingIndicatorWithFallback:()=>Xl,renderLucideIcon:()=>ge,resolveDockConfig:()=>Qn,resolveSanitizer:()=>As,resolveTokens:()=>hi,stripWebMcpPrefix:()=>Ka,themeToCssVariables:()=>yi,unregisterStreamAnimationPlugin:()=>Tg,validateImageFile:()=>zm,validateTheme:()=>Dl});module.exports=Ch(ev);var nm=require("marked"),rm=gl(require("dompurify"),1);var Zu=null,Cs=null,ws=null;var em=e=>{Cs=e},tm=()=>Cs?Promise.resolve(Cs):ws||(Zu?(ws=Zu().then(e=>(Cs=e,e)),ws):(ws=Promise.resolve().then(()=>(Yu(),Qu)).then(e=>(Cs=e,e)),ws)),Vo=()=>Cs;em({Marked:nm.Marked,DOMPurify:rm.default});var Ah=e=>{if(e)return e},na=e=>{let t=null;return n=>{var o,s;let r=Vo();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=Ah(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},Ko=e=>e?na({markedOptions:e.options,renderer:e.renderer}):na(),Sh=na(),fl=e=>Sh(e),Br=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),sm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),om=e=>`%%FORM_PLACEHOLDER_${e}%%`,am=(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=om(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=om(t.length);return t.push({token:s,type:o}),s}),n},im=e=>{let t=Ko(e);return n=>{let r=[],o=am(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="${sm(i)}"></div>`;s=s.replace(d,p)}),s}},lm=e=>{let t=[],n=am(e,t),r=fl(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="${sm(s)}"></div>`;r=r.replace(a,d)}),r};var Th={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"]},Eh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,hl=()=>{let e=null;return t=>{let n=Vo();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:")&&!Eh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Th)}},As=e=>e===!1?null:typeof e=="function"?e:hl();var cm=/^\s*\|?[\s:|-]*-[\s:|-]*$/,dm=e=>e.includes("|"),pm=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())},Mh=e=>`| ${e.join(" | ")} |`,kh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Lh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),um=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
1
|
+
"use strict";var yh=Object.create;var za=Object.defineProperty;var bh=Object.getOwnPropertyDescriptor;var xh=Object.getOwnPropertyNames;var vh=Object.getPrototypeOf,wh=Object.prototype.hasOwnProperty;var ta=(e,t)=>()=>(e&&(t=e(e=0)),t);var ml=(e,t)=>{for(var n in t)za(e,n,{get:t[n],enumerable:!0})},Gu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xh(t))!wh.call(e,o)&&o!==n&&za(e,o,{get:()=>t[o],enumerable:!(r=bh(t,o))||r.enumerable});return e};var gl=(e,t,n)=>(n=e!=null?yh(vh(e)):{},Gu(t||!e||!e.__esModule?za(n,"default",{value:e,enumerable:!0}):n,e)),Ch=e=>Gu(za({},"__esModule",{value:!0}),e);var Qu={};ml(Qu,{DOMPurify:()=>Xu.default,Marked:()=>Ju.Marked});var Ju,Xu,Yu=ta(()=>{"use strict";Ju=require("marked"),Xu=gl(require("dompurify"),1)});var Ls,Pl=ta(()=>{"use strict";Ls=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 Sy(e){return e.replace(/\/+$/,"")}async function Ty(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 pi,Ym=ta(()=>{"use strict";Pl();pi=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 Ls(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 g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let l=`${Sy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(l,{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 Ty(p));let u=p.body.getReader();for(;;){let{done:g,value:f}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let l=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,l),(i=r.onError)==null||i.call(r,l)}}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 ui,Zm=ta(()=>{"use strict";ui=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 eg={};ml(eg,{FallbackSpeechEngine:()=>ui,RuntypeSpeechEngine:()=>pi});var tg=ta(()=>{"use strict";Ym();Zm()});var ev={};ml(ev,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Ml,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>El,ASK_USER_QUESTION_TOOL_NAME:()=>aa,AgentWidgetClient:()=>Jo,AgentWidgetSession:()=>Is,AttachmentManager:()=>Zo,BrowserSpeechEngine:()=>So,DEFAULT_COMPONENTS:()=>Bl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>gi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Gn,DEFAULT_PALETTE:()=>Wl,DEFAULT_SEMANTIC:()=>Hl,DEFAULT_WIDGET_CONFIG:()=>Bt,PRESETS:()=>Ac,PRESET_FULLSCREEN:()=>Cc,PRESET_MINIMAL:()=>wc,PRESET_SHOP:()=>vc,ReadAloudController:()=>Yo,SUGGEST_REPLIES_CLIENT_TOOL:()=>Qa,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Al,SUGGEST_REPLIES_TOOL_NAME:()=>br,THEME_ZONES:()=>cg,VERSION:()=>lr,WEBMCP_TOOL_PREFIX:()=>yr,WebMcpBridge:()=>Ss,accessibilityPlugin:()=>If,animationsPlugin:()=>Rf,applyThemeVariables:()=>To,attachHeaderToContainer:()=>ts,brandPlugin:()=>Wf,buildComposer:()=>Ds,buildDefaultHeader:()=>Ul,buildHeader:()=>Zr,buildHeaderWithLayout:()=>Bs,buildMinimalHeader:()=>ql,builtInClientToolsForDispatch:()=>ca,collectEnrichedPageContext:()=>Lf,componentRegistry:()=>eo,createActionManager:()=>Wa,createAgentExperience:()=>Xi,createAskUserQuestionBubble:()=>Im,createBestAvailableVoiceProvider:()=>di,createBubbleWithLayout:()=>Bg,createCSATFeedback:()=>Ki,createComboButton:()=>Li,createComponentMiddleware:()=>df,createComponentStreamParser:()=>Ui,createDefaultSanitizer:()=>hl,createDemoCarousel:()=>Yf,createDirectivePostprocessor:()=>im,createDropdownMenu:()=>Lo,createFlexibleJsonStreamParser:()=>Bm,createIconButton:()=>Gt,createImagePart:()=>Um,createJsonStreamParser:()=>si,createLabelButton:()=>Ea,createLocalStorageAdapter:()=>ji,createMarkdownProcessor:()=>na,createMarkdownProcessorFromConfig:()=>Ko,createMessageActions:()=>Ql,createNPSFeedback:()=>Gi,createPlainTextParser:()=>ri,createPlugin:()=>Df,createRegexJsonParser:()=>oi,createStandardBubble:()=>Ns,createTextPart:()=>ma,createTheme:()=>Ws,createThemeObserver:()=>bi,createToggleGroup:()=>Ma,createTypingIndicator:()=>ns,createVoiceProvider:()=>Ao,createWidgetHostLayout:()=>Ha,createXmlParser:()=>ai,default:()=>Ff,defaultActionHandlers:()=>as,defaultJsonActionParser:()=>Ra,defaultParseRules:()=>bc,detectColorScheme:()=>ba,directivePostprocessor:()=>lm,ensureAskUserQuestionSheet:()=>Ms,escapeHtml:()=>Br,extractComponentDirectiveFromMessage:()=>Vi,fileToImagePart:()=>qm,formatEnrichedContext:()=>Pf,generateAssistantMessageId:()=>Xo,generateCodeSnippet:()=>zf,generateMessageId:()=>Om,generateStableSelector:()=>xc,generateUserMessageId:()=>ks,getActiveTheme:()=>Hs,getColorScheme:()=>Nl,getDisplayText:()=>_m,getHeaderLayout:()=>zl,getImageParts:()=>jm,getPreset:()=>Of,hasComponentDirective:()=>zi,hasImages:()=>$m,headerLayouts:()=>Pi,highContrastPlugin:()=>Bf,initAgentWidget:()=>gc,isAskUserQuestionMessage:()=>Gr,isComponentDirectiveType:()=>cf,isDockedMountMode:()=>on,isSuggestRepliesMessage:()=>la,isVoiceSupported:()=>fa,isWebMcpToolName:()=>yo,latestAgentSuggestions:()=>Ya,listRegisteredStreamAnimations:()=>Eg,markdownPostprocessor:()=>fl,mergeWithDefaults:()=>fi,normalizeContent:()=>Fm,parseAskUserQuestionPayload:()=>Jr,parseSuggestRepliesPayload:()=>Tl,pickBestVoice:()=>Ps,pluginRegistry:()=>Ia,reducedMotionPlugin:()=>Hf,registerStreamAnimationPlugin:()=>Sg,removeAskUserQuestionSheet:()=>vo,renderComponentDirective:()=>qi,renderLoadingIndicatorWithFallback:()=>Xl,renderLucideIcon:()=>ge,resolveDockConfig:()=>Jn,resolveSanitizer:()=>As,resolveTokens:()=>hi,stripWebMcpPrefix:()=>Ka,themeToCssVariables:()=>yi,unregisterStreamAnimationPlugin:()=>Tg,validateImageFile:()=>zm,validateTheme:()=>Dl});module.exports=Ch(ev);var nm=require("marked"),rm=gl(require("dompurify"),1);var Zu=null,Cs=null,ws=null;var em=e=>{Cs=e},tm=()=>Cs?Promise.resolve(Cs):ws||(Zu?(ws=Zu().then(e=>(Cs=e,e)),ws):(ws=Promise.resolve().then(()=>(Yu(),Qu)).then(e=>(Cs=e,e)),ws)),Vo=()=>Cs;em({Marked:nm.Marked,DOMPurify:rm.default});var Ah=e=>{if(e)return e},na=e=>{let t=null;return n=>{var o,s;let r=Vo();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=Ah(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},Ko=e=>e?na({markedOptions:e.options,renderer:e.renderer}):na(),Sh=na(),fl=e=>Sh(e),Br=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),sm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),om=e=>`%%FORM_PLACEHOLDER_${e}%%`,am=(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=om(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=om(t.length);return t.push({token:s,type:o}),s}),n},im=e=>{let t=Ko(e);return n=>{let r=[],o=am(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="${sm(i)}"></div>`;s=s.replace(d,p)}),s}},lm=e=>{let t=[],n=am(e,t),r=fl(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="${sm(s)}"></div>`;r=r.replace(a,d)}),r};var Th={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"]},Eh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,hl=()=>{let e=null;return t=>{let n=Vo();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:")&&!Eh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Th)}},As=e=>e===!1?null:typeof e=="function"?e:hl();var cm=/^\s*\|?[\s:|-]*-[\s:|-]*$/,dm=e=>e.includes("|"),pm=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())},Mh=e=>`| ${e.join(" | ")} |`,kh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Lh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),um=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
2
|
`),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!dm(o)||cm.test(o)||!cm.test(s))continue;let a=pm(o).length;if(a<1)continue;let i=kh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let l=t[d];if(l.trim()===""||!dm(l))break;let p=Mh(Lh(pm(l),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
|
|
3
|
-
`):e};var
|
|
3
|
+
`):e};var yr="webmcp:",yl=new Map,mm=e=>{var t;yl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&yl.set(n.name,r)}},ra=e=>yl.get(Ka(e)),Va={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},gm=null;function hm(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}:${Ph(t.join(""))}`}function fm(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 Ph(e){let t=fm(e,0).toString(36),n=fm(e,2654435761).toString(36);return`${t}.${n}`}var Ss=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 Va.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}mm(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=Rh(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 v=typeof document!="undefined"&&!!document.modelContext;return hr(v?"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=Ka(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return hr(`Failed to read WebMCP registry: ${x}`)}mm(a);let i=a.find(v=>v.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=ra(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let p=new AbortController,u=!1,g=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),f=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",f,{once:!0}));try{let v=await o.executeTool(i,Dh(n),{signal:p.signal});return Wh(v)}catch(v){if(u)return hr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return hr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(gm?await gm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Va.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,Va.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Hh;try{return await n(t)}catch(o){return Va.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=>Ih(t,r))}},Ka=e=>e.startsWith(yr)?e.slice(yr.length):e,yo=e=>e.startsWith(yr),Ih=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Rh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Wh=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:Nh(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),Hh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Bh(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)},Bh=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)}},Dh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Oh="agent_",Fh="flow_";function ym(e){return e.startsWith(Oh)?{kind:"agentId",agentId:e}:e.startsWith(Fh)?{kind:"flowId",flowId:e}:null}function bm(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 l=ym(i);if(l)return l;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=ym(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 bo=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 Et=(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},oa=(...e)=>e.filter(Boolean).join(" ");var aa="ask_user_question",sa=8,Ts="data-persona-ask-sheet-for",_h="Other",$h="Other\u2026",vm="Type your own answer here",wm="Send",jh="Next",Uh="Back",qh="Submit all",zh="Skip",Vh=3,bl="data-ask-current-index",xl="data-ask-question-count",Cm="data-ask-answers",vl="data-ask-grouped",Am="data-ask-layout",Kh=e=>e.layout==="pills"?"pills":"rows",Gh=e=>e.getAttribute(Am)==="pills"?"pills":"rows",xm=!1,Sm=e=>e.replace(/["\\]/g,"\\$&"),Jr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===aa,Ga=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,bo.parse)(o,bo.STR|bo.OBJ|bo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ia=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>sa&&!xm&&(xm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${sa}.`)),t.slice(0,sa)},Jh=e=>{var t;return(t=ia(e)[0])!=null?t:null},Xh=(e,t)=>{var n;return(n=ia(e)[t])!=null?n:null},Tm=(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))},Em=(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},Qh=(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 l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Em(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Yh=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},Zh=(e,t,n,r)=>{var p,u,g;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(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Vh;f++)s.appendChild(Yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(Qh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?_h:$h;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:vm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(M),v.appendChild(x);let E=Em(r,a,d.length);E&&v.appendChild(E),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Mm=(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:vm,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:wm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},ey=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:wm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ty=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Uh,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:zh,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:qh:(g=n.nextLabel)!=null?g:jh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(Cm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},km=(e,t)=>{e.setAttribute(Cm,JSON.stringify(t))},ir=e=>{var n;let t=Number((n=e.getAttribute(bl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ny=(e,t)=>{e.setAttribute(bl,String(Math.max(0,Math.floor(t))))},Es=e=>{var n;let t=Number((n=e.getAttribute(xl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(vl)==="true",ry=(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},oy=(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)))},Ja=(e,t)=>{let{payload:n}=Xr(t),r=ia(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Lm=e=>{let t=Go(e),n=ir(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 l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);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 l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),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=""},Pm=e=>{if(!xo(e))return;let t=Go(e),n=ir(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}},wl=(e,t,n)=>{let r=Ga(n),o=Gh(e),{payload:s,complete:a}=Xr(t),i=xo(e),d=ir(e),l=Es(e),p=i?Xh(s,d):Jh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let P=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=P,v.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let P=Zh(p,r,a,o);x.replaceWith(P)}if(o!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Mm(r,o))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(ey(r)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=ty(d,l,r);E?E.replaceWith(P):e.appendChild(P)}else E&&E.remove();Lm(e),Pm(e)},sy=(e,t,n)=>{let r=Ga(t),o=Kh(r),s=e.toolCall.id,a=ia(n),i=Math.max(1,a.length),d=i>1,l=ry(e,a),p=d?oy(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ts,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(xl,String(i)),u.setAttribute(bl,String(p)),u.setAttribute(vl,d?"true":"false"),u.setAttribute(Am,o),km(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Tm(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),o!=="rows"&&u.appendChild(Mm(r,o)),wl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ay=(e,t,n)=>{let{payload:r}=Xr(t),o=Math.max(1,ia(r).length);o>Es(e)&&(e.setAttribute(xl,String(o)),o>1&&!xo(e)&&e.setAttribute(vl,"true")),wl(e,t,n)},Im=(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=Ga(t);Tm(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},Ms=(e,t,n)=>{if(!n||!Jr(e)||Ga(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Ts}]`).forEach(l=>{l.getAttribute(Ts)!==o&&l.remove()});let a=n.querySelector(`[${Ts}="${Sm(o)}"]`);if(a){ay(a,e,t);return}let{payload:i}=Xr(e),d=sy(e,t,i);n.appendChild(d)},vo=(e,t)=>{if(!e)return;let n=t?`[${Ts}="${Sm(t)}"]`:`[${Ts}]`;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)})},Cl=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),wo=(e,t)=>{let n=Go(e),r=ir(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,km(e,n),Lm(e),Pm(e)},Xa=(e,t,n,r)=>{let o=Es(e),s=Math.max(0,Math.min(o-1,r));ny(e,s),wl(e,t,n)};var xr="suggest_replies";var Al={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},Qa={name:xr,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:Al,origin:"sdk",annotations:{readOnlyHint:!0}},Sl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),la=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===xr},Tl=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},Ya=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!la(r))continue;let o=Tl((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Rm=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 El={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:sa,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},Ml={name:aa,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:El,origin:"sdk",annotations:{readOnlyHint:!0}},ca=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(Ml),Rm(e)&&t.push(Qa),t};var Qr=require("partial-json"),Za=e=>e.replace(/\\n/g,`
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},Bh=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)}},Dh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Oh="agent_",Fh="flow_";function ym(e){return e.startsWith(Oh)?{kind:"agentId",agentId:e}:e.startsWith(Fh)?{kind:"flowId",flowId:e}:null}function bm(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 l=ym(i);if(l)return l;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=ym(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 bo=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 Tt=(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},oa=(...e)=>e.filter(Boolean).join(" ");var aa="ask_user_question",sa=8,Ts="data-persona-ask-sheet-for",_h="Other",$h="Other\u2026",vm="Type your own answer here",wm="Send",jh="Next",Uh="Back",qh="Submit all",zh="Skip",Vh=3,bl="data-ask-current-index",xl="data-ask-question-count",Cm="data-ask-answers",vl="data-ask-grouped",Am="data-ask-layout",Kh=e=>e.layout==="pills"?"pills":"rows",Gh=e=>e.getAttribute(Am)==="pills"?"pills":"rows",xm=!1,Sm=e=>e.replace(/["\\]/g,"\\$&"),Gr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===aa,Ga=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Jr=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,bo.parse)(o,bo.STR|bo.OBJ|bo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ia=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>sa&&!xm&&(xm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${sa}.`)),t.slice(0,sa)},Jh=e=>{var t;return(t=ia(e)[0])!=null?t:null},Xh=(e,t)=>{var n;return(n=ia(e)[t])!=null?n:null},Tm=(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))},Em=(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},Qh=(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 l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Em(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Yh=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},Zh=(e,t,n,r)=>{var p,u,g;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(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Vh;f++)s.appendChild(Yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(Qh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?_h:$h;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:vm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(M),v.appendChild(x);let E=Em(r,a,d.length);E&&v.appendChild(E),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Mm=(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:vm,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:wm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},ey=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:wm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ty=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Uh,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:zh,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:qh:(g=n.nextLabel)!=null?g:jh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(Cm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},km=(e,t)=>{e.setAttribute(Cm,JSON.stringify(t))},ir=e=>{var n;let t=Number((n=e.getAttribute(bl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ny=(e,t)=>{e.setAttribute(bl,String(Math.max(0,Math.floor(t))))},Es=e=>{var n;let t=Number((n=e.getAttribute(xl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(vl)==="true",ry=(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},oy=(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)))},Ja=(e,t)=>{let{payload:n}=Jr(t),r=ia(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Lm=e=>{let t=Go(e),n=ir(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 l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);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 l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),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=""},Pm=e=>{if(!xo(e))return;let t=Go(e),n=ir(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}},wl=(e,t,n)=>{let r=Ga(n),o=Gh(e),{payload:s,complete:a}=Jr(t),i=xo(e),d=ir(e),l=Es(e),p=i?Xh(s,d):Jh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let P=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=P,v.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let P=Zh(p,r,a,o);x.replaceWith(P)}if(o!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Mm(r,o))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(ey(r)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=ty(d,l,r);E?E.replaceWith(P):e.appendChild(P)}else E&&E.remove();Lm(e),Pm(e)},sy=(e,t,n)=>{let r=Ga(t),o=Kh(r),s=e.toolCall.id,a=ia(n),i=Math.max(1,a.length),d=i>1,l=ry(e,a),p=d?oy(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ts,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(xl,String(i)),u.setAttribute(bl,String(p)),u.setAttribute(vl,d?"true":"false"),u.setAttribute(Am,o),km(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Tm(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),o!=="rows"&&u.appendChild(Mm(r,o)),wl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ay=(e,t,n)=>{let{payload:r}=Jr(t),o=Math.max(1,ia(r).length);o>Es(e)&&(e.setAttribute(xl,String(o)),o>1&&!xo(e)&&e.setAttribute(vl,"true")),wl(e,t,n)},Im=(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=Ga(t);Tm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=Jr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ms=(e,t,n)=>{if(!n||!Gr(e)||Ga(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Ts}]`).forEach(l=>{l.getAttribute(Ts)!==o&&l.remove()});let a=n.querySelector(`[${Ts}="${Sm(o)}"]`);if(a){ay(a,e,t);return}let{payload:i}=Jr(e),d=sy(e,t,i);n.appendChild(d)},vo=(e,t)=>{if(!e)return;let n=t?`[${Ts}="${Sm(t)}"]`:`[${Ts}]`;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)})},Cl=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),wo=(e,t)=>{let n=Go(e),r=ir(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,km(e,n),Lm(e),Pm(e)},Xa=(e,t,n,r)=>{let o=Es(e),s=Math.max(0,Math.min(o-1,r));ny(e,s),wl(e,t,n)};var br="suggest_replies";var Al={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},Qa={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:Al,origin:"sdk",annotations:{readOnlyHint:!0}},Sl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),la=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===br},Tl=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},Ya=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!la(r))continue;let o=Tl((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Rm=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 El={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:sa,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},Ml={name:aa,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:El,origin:"sdk",annotations:{readOnlyHint:!0}},ca=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(Ml),Rm(e)&&t.push(Qa),t};var Xr=require("partial-json"),Za=e=>e.replace(/\\n/g,`
|
|
9
9
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Co=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)}},iy=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`},Wm=e=>e.status==="complete"?iy(e):e.status==="pending"?"Waiting":"",ly=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 Hm=e=>e.status==="complete"?ly(e):"Using tool...",ei=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},pa=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 ei(t)},ti=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 ei(t)},kl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=pa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},ni=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&da(r,n.slice(s,a.index),[]),a[1]!==void 0?da(r,a[1],["bold"]):a[2]!==void 0?da(r,a[2],["italic"]):a[3]!==void 0&&da(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&da(r,n.slice(s),[]),r},da=(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})},cy=()=>{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()=>{}}},ua=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ri=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},oi=()=>{var t;let e=cy();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)}},si=()=>{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"?Za(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Za(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Bm=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Za(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Za(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:()=>{}}},ai=()=>{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 Dm="4.4.0";var lr=Dm;var py="https://api.runtype.com/v1/dispatch",ii="https://api.runtype.com";function uy(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 Ll=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 my(e){switch(e){case"json":return si;case"regex-json":return oi;case"xml":return ai;default:return ri}}var Nm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function gy(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=Nm(n);if(!Nm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=ua(e);return ua(t)!==null&&a===null?t:e}var Jo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;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:py,this.headers={"Content-Type":"application/json","X-Persona-Version":lr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:my(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 Ss(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=bm(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$/,""))||ii}/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,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l: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":lr},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$/,""))||ii}/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":lr},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 k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Ll).map(k=>{var I,C,W;return{id:k.id,role:k.role,content:(W=(C=(I=k.contentParts)!=null?I:k.llmContent)!=null?C:k.rawContent)!=null?W:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?hm(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,M=f&&x&&this.lastSentClientToolsFingerprint===v,E=!1,P=null,L;for(let k=0;;k++){let C={...u,...f&&(E||!M)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(C),signal:r.signal}),L.status===409&&k===0&&f){let W=await L.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=W!=null?W:{error:"Chat request failed"}}break}if(!L.ok){let k=P!=null?P:await L.json().catch(()=>({error:"Chat request failed"}));if(L.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(L.status===429){let C=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let I=new Error(k.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!L.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}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){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/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 l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ii}/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(Ll).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ca(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 l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Ll).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l: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,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...ca(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 l=>{try{let p=await l({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 l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}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},l=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=l(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){var Dt,Yt,Or,wr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=S=>{let ne=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,Me=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,De=S.tools?S.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...S,reasoning:ne,toolCall:Me,tools:De}},u=S=>{if(S.role!=="assistant"||S.variant)return!0;let ne=Array.isArray(S.contentParts)&&S.contentParts.length>0,Me=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||ne||Me||!!S.stopReason},g=S=>{u(S)&&n({type:"message",message:p(S)})},f=null,v=null,x={current:null},M={current:null},E=null,P="",L=new Map,k=new Map,I=new Map,C=new Map,W=new Map,_={lastId:null,byStep:new Map},U={lastId:null,byCall:new Map},H=S=>{if(S==null)return null;try{return String(S)}catch{return null}},F=S=>{var ne,Me,De,Pe,Ne;return H((Ne=(Pe=(De=(Me=(ne=S.stepId)!=null?ne:S.step_id)!=null?Me:S.step)!=null?De:S.parentId)!=null?Pe:S.flowStepId)!=null?Ne:S.flow_step_id)},O=S=>{var ne,Me,De,Pe,Ne,Je,lt;return H((lt=(Je=(Ne=(Pe=(De=(Me=(ne=S.callId)!=null?ne:S.call_id)!=null?Me:S.requestId)!=null?De:S.request_id)!=null?Pe:S.toolCallId)!=null?Ne:S.tool_call_id)!=null?Je:S.stepId)!=null?lt:S.step_id)},ee=r,Ee=!1,ue=()=>{if(f)return f;let S,ne=E;return!Ee&&ee?(S=ee,Ee=!0):ee&&ne?S=`${ee}_${ne}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:S,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},te=(S,ne)=>{_.lastId=ne,S&&_.byStep.set(S,ne)},ve=(S,ne)=>{var Ne;let Me=(Ne=S.reasoningId)!=null?Ne:S.id,De=F(S);if(Me){let Je=String(Me);return te(De,Je),Je}if(De){let Je=_.byStep.get(De);if(Je)return _.lastId=Je,Je}if(_.lastId&&!ne)return _.lastId;if(!ne)return null;let Pe=`reason-${l()}`;return te(De,Pe),Pe},ke=S=>{let ne=C.get(S);if(ne)return ne;let Me={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:S,status:"streaming",chunks:[]}};return C.set(S,Me),g(Me),Me},se=(S,ne)=>{U.lastId=ne,S&&U.byCall.set(S,ne)},xe=new Set,pe=new Map,ie=new Set,ae=new Map,He=S=>{if(!S)return!1;let ne=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return ne==="emit_artifact_markdown"||ne==="emit_artifact_component"},Fe=(S,ne)=>{var Ne;let Me=(Ne=S.toolId)!=null?Ne:S.id,De=O(S);if(Me){let Je=String(Me);return se(De,Je),Je}if(De){let Je=U.byCall.get(De);if(Je)return U.lastId=Je,Je}if(U.lastId&&!ne)return U.lastId;if(!ne)return null;let Pe=`tool-${l()}`;return se(De,Pe),Pe},K=S=>{let ne=W.get(S);if(ne)return ne;let Me={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:S,status:"pending"}};return W.set(S,Me),g(Me),Me},G=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let ne=Number(S);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let Me=Date.parse(S);if(!Number.isNaN(Me))return Me}return Date.now()},we=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},X=new Map,de=new Map,We=new Map,fe=(S,ne,Me)=>{var lt;let De=We.get(S);De||(De=[],We.set(S,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<ne?Pe=It+1:Ne=It}((lt=De[Pe])==null?void 0:lt.seq)===ne?De[Pe]={seq:ne,text:Me}:De.splice(Pe,0,{seq:ne,text:Me});let Je="";for(let It=0;It<De.length;It++)Je+=De[It].text;return Je},Ge=(S,ne)=>{let Me=we(ne),De=de.get(S.id),Pe=gy(De,Me);S.rawContent=Pe;let Ne=X.get(S.id),Je=Y=>{var ct;let Te=(ct=S.content)!=null?ct:"";Y.trim()!==""&&(Te.trim().length===0||Y.startsWith(Te)||Y.trimStart().startsWith(Te.trim()))&&(S.content=Y)},lt=()=>{var Y;if(Ne){let Te=(Y=Ne.close)==null?void 0:Y.call(Ne);Te instanceof Promise&&Te.catch(()=>{})}X.delete(S.id),de.delete(S.id),S.streaming=!1,g(S)};if(!Ne){Je(Me),lt();return}let It=ua(Pe);if(It!==null&&It.trim()!==""){Je(It),lt();return}let xt=Y=>{var Ye;let Te=typeof Y=="string"?Y:(Ye=Y==null?void 0:Y.text)!=null?Ye:null;if(Te!==null&&Te.trim()!=="")return Te;let ct=Ne.getExtractedText();return ct!==null&&ct.trim()!==""?ct:Me},B;try{B=Ne.processChunk(Pe)}catch{Je(Me),lt();return}if(B instanceof Promise){B.then(Y=>{Je(xt(Y)),lt()}).catch(()=>{Je(Me),lt()});return}Je(xt(B)),lt()},nt=null,Pt=(S,ne,Me,De)=>{var It;S.rawContent=ne,X.has(S.id)||X.set(S.id,this.createStreamParser());let Pe=X.get(S.id),Ne=ne.trim().startsWith("{")||ne.trim().startsWith("[");if(Ne&&de.set(S.id,ne),Pe.__isPlainTextParser===!0){S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S);return}let lt=Pe.processChunk(ne);if(lt instanceof Promise)lt.then(xt=>{var Y;let B=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;B!==null&&B.trim()!==""?(S.content=B,g(S)):!Ne&&!ne.trim().startsWith("<")&&(S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S))}).catch(()=>{S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S)});else{let xt=typeof lt=="string"?lt:(It=lt==null?void 0:lt.text)!=null?It:null;xt!==null&&xt.trim()!==""?(S.content=xt,g(S)):!Ne&&!ne.trim().startsWith("<")&&(S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S))}},Ze=(S,ne)=>{var It,xt;let Me=ne!=null?ne:S.content;if(Me==null||Me===""){S.streaming=!1,g(S);return}let De=de.get(S.id),Pe=De!=null?De:we(Me);S.rawContent=Pe;let Ne=X.get(S.id),Je=null,lt=!1;if(Ne&&(Je=Ne.getExtractedText(),Je===null&&(Je=ua(Pe)),Je===null)){let B=Ne.processChunk(Pe);B instanceof Promise?(lt=!0,B.then(Y=>{var ct;let Te=typeof Y=="string"?Y:(ct=Y==null?void 0:Y.text)!=null?ct:null;Te!==null&&(S.content=Te,S.streaming=!1,X.delete(S.id),de.delete(S.id),g(S))}).catch(()=>{})):Je=typeof B=="string"?B:(It=B==null?void 0:B.text)!=null?It:null}if(!lt){Je!==null&&Je.trim()!==""?S.content=Je:de.has(S.id)||(S.content=we(Me));let B=X.get(S.id);if(B){let Y=(xt=B.close)==null?void 0:xt.call(B);Y instanceof Promise&&Y.catch(()=>{}),X.delete(S.id)}de.delete(S.id),S.streaming=!1,g(S)}},$e=(S,ne,Me)=>{let De=k.get(S);if(De)return De;let Pe={id:`nested-${ne}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ne}};return k.set(S,Pe),g(Pe),Pe},J=[],Ve,ze=new Map,Ce=0,Se="agent",rt=!1,_t=null,re=null,je=new Map,yn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(Ve=()=>{var S,ne,Me,De,Pe,Ne,Je,lt,It,xt,B,Y,Te,ct,Ye,Ut,bn,vt,wt,Rt,Ct,pn,$t,On,Tn,En,vn,Mn,dr,At,Cr,Ar,Fr,pr,mt,Io,Sr,Ro,Wn,is,ro,_r,oo,so,Wo,Ho,ao,bt,Fn,_n,kn,St,Zn,er,$n,io,$r,lo,jn,Wt,Ln,tr,co,jr,po,ye,Hn,Tr,gt,sn,an,Er,Us,Ur,Bo,Mr,j,ls,kr,Lr,qr,Pr,ur,cs,Da,Un,qn,mr,gr,Do,zr,wn,Ir,ds,No,ps,Na,us,Oa,ms,ut,qs,nr,Bn,Fa;for(let gs=0;gs<J.length;gs++){let tt=J[gs].payloadType,w=J[gs].payload;if(!rt&&Se!=="flow"&&typeof w.stepType=="string"&&(Se="flow"),tt==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q),$e(V,q,"reasoning");continue}let Q=(S=ve(w,!0))!=null?S:`reason-${l()}`,he=ke(Q);he.reasoning=(ne=he.reasoning)!=null?ne:{id:Q,status:"streaming",chunks:[]},he.reasoning.startedAt=(De=he.reasoning.startedAt)!=null?De:G((Me=w.startedAt)!=null?Me:w.timestamp),he.reasoning.completedAt=void 0,he.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),he.streaming=!0,he.reasoning.status="streaming",g(he)}else if(tt==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let _e=k.get(V),ft=(Je=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Je:"";ft&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(ft)),g(_e));continue}let q=(It=(lt=ve(w,!1))!=null?lt:ve(w,!0))!=null?It:`reason-${l()}`,Q=ke(q);Q.reasoning=(xt=Q.reasoning)!=null?xt:{id:q,status:"streaming",chunks:[]},Q.reasoning.startedAt=(Y=Q.reasoning.startedAt)!=null?Y:G((B=w.startedAt)!=null?B:w.timestamp);let he=(Ye=(ct=(Te=w.reasoningText)!=null?Te:w.text)!=null?ct:w.delta)!=null?Ye:"";if(he&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let ft=fe(q,_e,String(he));Q.reasoning.chunks=[ft]}else Q.reasoning.chunks.push(String(he))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=G((Ut=w.completedAt)!=null?Ut:w.timestamp);let _e=(bn=Q.reasoning.startedAt)!=null?bn:Date.now();Q.reasoning.durationMs=Math.max(0,((vt=Q.reasoning.completedAt)!=null?vt:Date.now())-_e)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(tt==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let ft=k.get(V);if(ft.reasoning){let at=typeof w.text=="string"?w.text:"";at&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(at),ft.reasoning.status="complete",ft.streaming=!1,g(ft)}L.delete(V),k.delete(V);continue}let q=(Rt=(wt=ve(w,!1))!=null?wt:ve(w,!0))!=null?Rt:`reason-${l()}`,Q=typeof w.text=="string"?w.text:"";!C.get(q)&&(Q||w.scope==="loop")&&ke(q);let he=C.get(q);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),Q&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(Q),he.reasoning.status="complete",he.reasoning.completedAt=G((Ct=w.completedAt)!=null?Ct:w.timestamp);let ft=(pn=he.reasoning.startedAt)!=null?pn:Date.now();he.reasoning.durationMs=Math.max(0,(($t=he.reasoning.completedAt)!=null?$t:Date.now())-ft),he.streaming=!1,g(he)}let _e=F(w);_e&&_.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(Tn=(On=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?On:Fe(w,!0))!=null?Tn:`tool-${l()}`,q=(En=w.toolName)!=null?En:w.name;if(He(q)){xe.add(V);continue}se(O(w),V);let Q=K(V),he=(vn=Q.toolCall)!=null?vn:{id:V,status:"pending"};he.name=q!=null?q:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(dr=he.startedAt)!=null?dr:G((Mn=w.startedAt)!=null?Mn:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,Q.toolCall=he,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(tt==="tool_output_delta"){let V=(Cr=(At=Fe(w,!1))!=null?At:Fe(w,!0))!=null?Cr:`tool-${l()}`;if(xe.has(V))continue;let q=K(V),Q=(Ar=q.toolCall)!=null?Ar:{id:V,status:"running"};Q.startedAt=(pr=Q.startedAt)!=null?pr:G((Fr=w.startedAt)!=null?Fr:w.timestamp);let he=(Sr=(Io=(mt=w.text)!=null?mt:w.delta)!=null?Io:w.message)!=null?Sr:"";he&&(Q.chunks=(Ro=Q.chunks)!=null?Ro:[],Q.chunks.push(String(he))),Q.status="running",q.toolCall=Q,q.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(q.agentMetadata=(ro=q.agentMetadata)!=null?ro:{executionId:(Wn=_e==null?void 0:_e.executionId)!=null?Wn:w.executionId,iteration:(is=_e==null?void 0:_e.iteration)!=null?is:w.iteration}),g(q)}else if(tt==="tool_complete"){let V=(oo=(_r=Fe(w,!1))!=null?_r:Fe(w,!0))!=null?oo:`tool-${l()}`;if(xe.has(V)){xe.delete(V);continue}let q=K(V),Q=(so=q.toolCall)!=null?so:{id:V,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=G((Wo=w.completedAt)!=null?Wo:w.timestamp);let he=(Ho=w.duration)!=null?Ho:w.executionTime;if(typeof he=="number")Q.durationMs=he;else{let at=(ao=Q.startedAt)!=null?ao:Date.now();Q.durationMs=Math.max(0,((bt=Q.completedAt)!=null?bt:Date.now())-at)}q.toolCall=Q,q.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(q.agentMetadata=(kn=q.agentMetadata)!=null?kn:{executionId:(Fn=_e==null?void 0:_e.executionId)!=null?Fn:w.executionId,iteration:(_n=_e==null?void 0:_e.iteration)!=null?_n:w.iteration}),g(q);let ft=O(w);ft&&U.byCall.delete(ft)}else if(tt==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(St=V!=null?V:w.toolId)!=null?St:`local-${l()}`,Q=K(q),he=w.toolName,_e=w.origin==="webmcp"&&!yo(he)?`webmcp:${he}`:he,ft=yo(_e),at=(Zn=Q.toolCall)!=null?Zn:{id:q,status:"pending"};at.name=_e,at.args=w.parameters,at.status=ft?"running":"complete",at.chunks=(er=at.chunks)!=null?er:[],at.startedAt=($r=at.startedAt)!=null?$r:G((io=($n=w.startedAt)!=null?$n:w.timestamp)!=null?io:w.awaitedAt),ft?(at.completedAt=void 0,at.duration=void 0,at.durationMs=void 0):at.completedAt=(lo=at.completedAt)!=null?lo:at.startedAt,Q.toolCall=at,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Wt=w.executionId)!=null?Wt:(jn=Q.agentMetadata)==null?void 0:jn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(Q)}else if(tt==="text_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q);continue}let Q=f;Q&&(Se==="flow"?(Ze(Q),nt=Q):(Q.streaming=!1,g(Q)),f=null),E=typeof w.id=="string"?w.id:E,P=""}else if(tt==="text_delta"){let V=typeof w.id=="string"?w.id:null,q=V?L.get(V):void 0;if(V&&q){let he=typeof w.delta=="string"?w.delta:"",_e=((Ln=I.get(V))!=null?Ln:"")+he;if(I.set(V,_e),_e.trim()==="")continue;let ft=$e(V,q);ft.agentMetadata={...ft.agentMetadata,executionId:w.executionId,parentToolId:q},Pt(ft,_e,he,void 0);continue}if(E=typeof w.id=="string"?w.id:E,Se==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(P+=he,P.trim()==="")continue;let _e=ue();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},Pt(_e,P,he,void 0),v=_e;continue}let Q=ue();Q.content+=(tr=w.delta)!=null?tr:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:_t!=null?_t:void 0,agentName:re==null?void 0:re.agentName},v=Q,g(Q)}else if(tt==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)){let Q=k.get(V);Q&&Ze(Q),L.delete(V),I.delete(V),k.delete(V);continue}let q=f;q&&(Se==="flow"?(Ze(q),nt=q):(((co=q.content)!=null?co:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),f=null),E=null,P=""}else if(tt==="step_complete"){let V=w.stepType,q=w.executionType;if(V==="tool"||q==="context")continue;if(w.success===!1){let Q=w.error,he=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((jr=Q.message)!=null?jr:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let Q=nt;nt=null;let he=w.stopReason,_e=(po=w.result)==null?void 0:po.response;if(Q)he&&(Q.stopReason=he),_e!=null?Ge(Q,_e):Q.streaming!==!1&&(X.delete(Q.id),de.delete(Q.id),Q.streaming=!1,g(Q));else{let ft=_e!=null&&_e!=="";if(ft||he){let at=ue();he&&(at.stopReason=he),ft?Ze(at,_e):(at.streaming=!1,g(at))}}continue}}else if(tt==="execution_start")Se=w.kind==="flow"?"flow":"agent",rt=!0,Se==="agent"&&(re={executionId:w.executionId,agentId:(ye=w.agentId)!=null?ye:"virtual",agentName:(Hn=w.agentName)!=null?Hn:"",status:"running",currentIteration:0,maxTurns:(Tr=w.maxTurns)!=null?Tr:1,startedAt:G(w.startedAt)});else if(tt==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(re&&(re.currentIteration=V),yn==="separate"&&V>1){let q=f;q&&(q.streaming=!1,g(q),je.set(V-1,q),f=null)}Ce=V}_t=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let V=(gt=w.toolCallId)!=null?gt:U.lastId;if(V){let q=W.get(V);q!=null&&q.toolCall&&(q.toolCall.chunks=(sn=q.toolCall.chunks)!=null?sn:[],q.toolCall.chunks.push((an=w.delta)!=null?an:""),g(q))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let V=w.stopReason,q=f!=null?f:v;if(V&&q!==null){let Q=w.id;(!Q||((Er=q.agentMetadata)==null?void 0:Er.turnId)===Q)&&(q.stopReason=V,g(q))}_t===w.id&&(_t=null)}else if(tt==="media_start"){let V=String(w.id);ze.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(tt==="media_delta"){let V=ze.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(tt==="media_complete"){let V=String(w.id),q=ze.get(V);ze.delete(V);let Q=(Ur=(Us=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Us:q==null?void 0:q.mediaType)!=null?Ur:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,ft=null;if(he)ft={type:"media",data:he,mediaType:Q};else if(_e){let un=Q.toLowerCase();ft={type:un==="image"||un.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:Q}}let at=(Bo=w.toolCallId)!=null?Bo:q==null?void 0:q.toolCallId,zs=ft?[ft]:[],Dn=[];for(let un of zs){if(!un||typeof un!="object")continue;let mn=un,Oo=typeof mn.type=="string"?mn.type:void 0,Vr=typeof mn.mediaType=="string"?mn.mediaType.toLowerCase():"",Pn=null,xn="";if(Oo==="media"){let zn=typeof mn.data=="string"?mn.data:void 0;if(!zn)continue;xn=Vr.length>0?Vr:"application/octet-stream",Pn=`data:${xn};base64,${zn}`}else if(Oo==="image-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;xn=Vr,Pn=zn}else if(Oo==="file-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;xn=Vr,Pn=zn}else continue;if(Pn)if(Oo==="image-url"||xn.startsWith("image/"))Dn.push({type:"image",image:Pn,...xn.includes("/")?{mimeType:xn}:{}});else if(xn.startsWith("audio/"))Dn.push({type:"audio",audio:Pn,mimeType:xn});else if(xn.startsWith("video/"))Dn.push({type:"video",video:Pn,mimeType:xn});else{let zn=xn||"application/octet-stream";Dn.push({type:"file",data:Pn,mimeType:zn,filename:uy(zn)})}}if(Dn.length>0){let un=l(),mn=at,Vr={id:`agent-media-${typeof mn=="string"&&mn.length>0?`${mn}-${un}`:String(un)}`,role:"assistant",content:"",contentParts:Dn,createdAt:new Date().toISOString(),streaming:!1,sequence:un,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Vr);let Pn=f;Pn&&(Pn.streaming=!1,g(Pn)),f=null,x.current=null}}else if(tt==="execution_complete"){let V=(Mr=w.kind)!=null?Mr:Se;V==="agent"&&re&&(re.status=w.success?"complete":"error",re.completedAt=G(w.completedAt),re.stopReason=w.stopReason);let q=f;q&&(V==="flow"&&q.streaming!==!1?Ze(q):(q.streaming=!1,g(q)),f=null),E=null,P="",nt=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let V=typeof w.error=="string"?w.error:(ls=(j=w.error)==null?void 0:j.message)!=null?ls:"Execution error";n({type:"error",error:new Error(V)})}else if(tt!=="ping"){if(tt==="approval_start"){let V=(kr=w.approvalId)!=null?kr:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Lr=re==null?void 0:re.agentId)!=null?Lr:"virtual",executionId:(Pr=(qr=w.executionId)!=null?qr:re==null?void 0:re.executionId)!=null?Pr:"",toolName:(ur=w.toolName)!=null?ur:"",toolType:w.toolType,description:(Da=w.description)!=null?Da:`Execute ${(cs=w.toolName)!=null?cs:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let V=(Un=w.approvalId)!=null?Un:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(qn=re==null?void 0:re.agentId)!=null?qn:"virtual",executionId:(gr=(mr=w.executionId)!=null?mr:re==null?void 0:re.executionId)!=null?gr:"",toolName:(Do=w.toolName)!=null?Do:"",toolType:w.toolType,description:(wn=w.description)!=null?wn:`Execute ${(zr=w.toolName)!=null?zr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(tt==="approval_complete"){let V=w.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:(Ir=w.decision)!=null?Ir:"approved",agentId:(ds=re==null?void 0:re.agentId)!=null?ds:"virtual",executionId:(ps=(No=w.executionId)!=null?No:re==null?void 0:re.executionId)!=null?ps:"",toolName:(Na=w.toolName)!=null?Na:"",description:(us=w.description)!=null?us:"",resolvedAt:Date.now()}};g(Q)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let V=w.artifactType,q=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:V,title:Q,component:typeof w.component=="string"?w.component:void 0}),ae.set(q,{markdown:"",title:Q}),!ie.has(q)){ie.add(q);let he={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:Q,artifactType:V,status:"streaming"}})};pe.set(q,he),g(he)}}else if(tt==="artifact_delta"){let V=String(w.id),q=typeof w.delta=="string"?w.delta:String((Oa=w.delta)!=null?Oa:"");n({type:"artifact_delta",id:V,artDelta:q});let Q=ae.get(V);Q&&(Q.markdown+=q)}else if(tt==="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(tt==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let q=pe.get(V);if(q){q.streaming=!1;try{let Q=JSON.parse((ms=q.rawContent)!=null?ms:"{}");if(Q.props){Q.props.status="complete";let he=ae.get(V);he!=null&&he.markdown&&(Q.props.markdown=he.markdown)}q.rawContent=JSON.stringify(Q)}catch{}ae.delete(V),g(q),pe.delete(V)}}}else if(tt==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let q=String((ut=V.id)!=null?ut:`msg-${l()}`),Q=V.role,_e={id:q,role:Q==="user"?"user":Q==="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:l()};if(g(_e),_e.rawContent)try{let ft=JSON.parse(_e.rawContent),at=(qs=ft==null?void 0:ft.props)==null?void 0:qs.artifactId;typeof at=="string"&&ie.add(at)}catch{}f=null,x.current=null,X.delete(q),de.delete(q)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((nr=w.error)==null?void 0:nr.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(tt==="dispatch_error"){let q=(Bn=w.message)!=null?Bn:w.error;q!=null&&q!==""&&(V=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?V=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(V=new Error(String((Fa=q.message)!=null?Fa:q)))}if(V){n({type:"error",error:V});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:S,value:ne}=await o.read();if(S)break;a+=s.decode(ne,{stream:!0});let Me=a.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()=>{}}},ua=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ri=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},oi=()=>{var t;let e=cy();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)}},si=()=>{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,Xr.parse)(n,Xr.STR|Xr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Za(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Za(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Bm=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Za(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Za(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,Xr.parse)(s,Xr.STR|Xr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ai=()=>{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 Dm="4.4.1";var lr=Dm;var py="https://api.runtype.com/v1/dispatch",ii="https://api.runtype.com";function uy(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 Ll=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 my(e){switch(e){case"json":return si;case"regex-json":return oi;case"xml":return ai;default:return ri}}var Nm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function gy(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=Nm(n);if(!Nm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=ua(e);return ua(t)!==null&&a===null?t:e}var Jo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;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:py,this.headers={"Content-Type":"application/json","X-Persona-Version":lr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:my(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 Ss(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=bm(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$/,""))||ii}/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,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l: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":lr},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$/,""))||ii}/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":lr},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 k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Ll).map(k=>{var I,C,W;return{id:k.id,role:k.role,content:(W=(C=(I=k.contentParts)!=null?I:k.llmContent)!=null?C:k.rawContent)!=null?W:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?hm(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,M=f&&x&&this.lastSentClientToolsFingerprint===v,E=!1,P=null,L;for(let k=0;;k++){let C={...u,...f&&(E||!M)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(C),signal:r.signal}),L.status===409&&k===0&&f){let W=await L.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=W!=null?W:{error:"Chat request failed"}}break}if(!L.ok){let k=P!=null?P:await L.json().catch(()=>({error:"Chat request failed"}));if(L.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(L.status===429){let C=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let I=new Error(k.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!L.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}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){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/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 l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ii}/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(Ll).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ca(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 l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Ll).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l: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,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...ca(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 l=>{try{let p=await l({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 l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}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},l=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=l(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){var vt,yn,vr,wr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=S=>{let ne=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,Ee=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,Ne=S.tools?S.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...S,reasoning:ne,toolCall:Ee,tools:Ne}},u=S=>{if(S.role!=="assistant"||S.variant)return!0;let ne=Array.isArray(S.contentParts)&&S.contentParts.length>0,Ee=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||ne||Ee||!!S.stopReason},g=S=>{u(S)&&n({type:"message",message:p(S)})},f=null,v=null,x={current:null},M={current:null},E=null,P="",L=new Map,k=new Map,I=new Map,C=new Map,W=new Map,_={lastId:null,byStep:new Map},U={lastId:null,byCall:new Map},H=S=>{if(S==null)return null;try{return String(S)}catch{return null}},F=S=>{var ne,Ee,Ne,Ie,Oe;return H((Oe=(Ie=(Ne=(Ee=(ne=S.stepId)!=null?ne:S.step_id)!=null?Ee:S.step)!=null?Ne:S.parentId)!=null?Ie:S.flowStepId)!=null?Oe:S.flow_step_id)},O=S=>{var ne,Ee,Ne,Ie,Oe,Je,lt;return H((lt=(Je=(Oe=(Ie=(Ne=(Ee=(ne=S.callId)!=null?ne:S.call_id)!=null?Ee:S.requestId)!=null?Ne:S.request_id)!=null?Ie:S.toolCallId)!=null?Oe:S.tool_call_id)!=null?Je:S.stepId)!=null?lt:S.step_id)},Z=r,Me=!1,pe=()=>{if(f)return f;let S,ne=E;return!Me&&Z?(S=Z,Me=!0):Z&&ne?S=`${Z}_${ne}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:S,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},ee=(S,ne)=>{_.lastId=ne,S&&_.byStep.set(S,ne)},Ae=(S,ne)=>{var Oe;let Ee=(Oe=S.reasoningId)!=null?Oe:S.id,Ne=F(S);if(Ee){let Je=String(Ee);return ee(Ne,Je),Je}if(Ne){let Je=_.byStep.get(Ne);if(Je)return _.lastId=Je,Je}if(_.lastId&&!ne)return _.lastId;if(!ne)return null;let Ie=`reason-${l()}`;return ee(Ne,Ie),Ie},Le=S=>{let ne=C.get(S);if(ne)return ne;let Ee={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:S,status:"streaming",chunks:[]}};return C.set(S,Ee),g(Ee),Ee},oe=(S,ne)=>{U.lastId=ne,S&&U.byCall.set(S,ne)},Ce=new Set,ce=new Map,ae=new Set,se=new Map,xe=S=>{if(!S)return!1;let ne=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return ne==="emit_artifact_markdown"||ne==="emit_artifact_component"},Be=(S,ne)=>{var Oe;let Ee=(Oe=S.toolId)!=null?Oe:S.id,Ne=O(S);if(Ee){let Je=String(Ee);return oe(Ne,Je),Je}if(Ne){let Je=U.byCall.get(Ne);if(Je)return U.lastId=Je,Je}if(U.lastId&&!ne)return U.lastId;if(!ne)return null;let Ie=`tool-${l()}`;return oe(Ne,Ie),Ie},K=S=>{let ne=W.get(S);if(ne)return ne;let Ee={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:S,status:"pending"}};return W.set(S,Ee),g(Ee),Ee},Q=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let ne=Number(S);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let Ee=Date.parse(S);if(!Number.isNaN(Ee))return Ee}return Date.now()},He=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},G=new Map,ue=new Map,je=new Map,fe=(S,ne,Ee)=>{var lt;let Ne=je.get(S);Ne||(Ne=[],je.set(S,Ne));let Ie=0,Oe=Ne.length;for(;Ie<Oe;){let Rt=Ie+Oe>>>1;Ne[Rt].seq<ne?Ie=Rt+1:Oe=Rt}((lt=Ne[Ie])==null?void 0:lt.seq)===ne?Ne[Ie]={seq:ne,text:Ee}:Ne.splice(Ie,0,{seq:ne,text:Ee});let Je="";for(let Rt=0;Rt<Ne.length;Rt++)Je+=Ne[Rt].text;return Je},Ke=(S,ne)=>{let Ee=He(ne),Ne=ue.get(S.id),Ie=gy(Ne,Ee);S.rawContent=Ie;let Oe=G.get(S.id),Je=ye=>{var wt;let _e=(wt=S.content)!=null?wt:"";ye.trim()!==""&&(_e.trim().length===0||ye.startsWith(_e)||ye.trimStart().startsWith(_e.trim()))&&(S.content=ye)},lt=()=>{var ye;if(Oe){let _e=(ye=Oe.close)==null?void 0:ye.call(Oe);_e instanceof Promise&&_e.catch(()=>{})}G.delete(S.id),ue.delete(S.id),S.streaming=!1,g(S)};if(!Oe){Je(Ee),lt();return}let Rt=ua(Ie);if(Rt!==null&&Rt.trim()!==""){Je(Rt),lt();return}let de=ye=>{var Ze;let _e=typeof ye=="string"?ye:(Ze=ye==null?void 0:ye.text)!=null?Ze:null;if(_e!==null&&_e.trim()!=="")return _e;let wt=Oe.getExtractedText();return wt!==null&&wt.trim()!==""?wt:Ee},B;try{B=Oe.processChunk(Ie)}catch{Je(Ee),lt();return}if(B instanceof Promise){B.then(ye=>{Je(de(ye)),lt()}).catch(()=>{Je(Ee),lt()});return}Je(de(B)),lt()},tt=null,jt=(S,ne,Ee,Ne)=>{var Rt;S.rawContent=ne,G.has(S.id)||G.set(S.id,this.createStreamParser());let Ie=G.get(S.id),Oe=ne.trim().startsWith("{")||ne.trim().startsWith("[");if(Oe&&ue.set(S.id,ne),Ie.__isPlainTextParser===!0){S.content=Ne!==void 0?ne:S.content+Ee,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S);return}let lt=Ie.processChunk(ne);if(lt instanceof Promise)lt.then(de=>{var ye;let B=typeof de=="string"?de:(ye=de==null?void 0:de.text)!=null?ye:null;B!==null&&B.trim()!==""?(S.content=B,g(S)):!Oe&&!ne.trim().startsWith("<")&&(S.content=Ne!==void 0?ne:S.content+Ee,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S))}).catch(()=>{S.content=Ne!==void 0?ne:S.content+Ee,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S)});else{let de=typeof lt=="string"?lt:(Rt=lt==null?void 0:lt.text)!=null?Rt:null;de!==null&&de.trim()!==""?(S.content=de,g(S)):!Oe&&!ne.trim().startsWith("<")&&(S.content=Ne!==void 0?ne:S.content+Ee,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S))}},Qe=(S,ne)=>{var Rt,de;let Ee=ne!=null?ne:S.content;if(Ee==null||Ee===""){S.streaming=!1,g(S);return}let Ne=ue.get(S.id),Ie=Ne!=null?Ne:He(Ee);S.rawContent=Ie;let Oe=G.get(S.id),Je=null,lt=!1;if(Oe&&(Je=Oe.getExtractedText(),Je===null&&(Je=ua(Ie)),Je===null)){let B=Oe.processChunk(Ie);B instanceof Promise?(lt=!0,B.then(ye=>{var wt;let _e=typeof ye=="string"?ye:(wt=ye==null?void 0:ye.text)!=null?wt:null;_e!==null&&(S.content=_e,S.streaming=!1,G.delete(S.id),ue.delete(S.id),g(S))}).catch(()=>{})):Je=typeof B=="string"?B:(Rt=B==null?void 0:B.text)!=null?Rt:null}if(!lt){Je!==null&&Je.trim()!==""?S.content=Je:ue.has(S.id)||(S.content=He(Ee));let B=G.get(S.id);if(B){let ye=(de=B.close)==null?void 0:de.call(B);ye instanceof Promise&&ye.catch(()=>{}),G.delete(S.id)}ue.delete(S.id),S.streaming=!1,g(S)}},he=(S,ne,Ee)=>{let Ne=k.get(S);if(Ne)return Ne;let Ie={id:`nested-${ne}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ne}};return k.set(S,Ie),g(Ie),Ie},X=[],pt,ze=new Map,Se=0,ke="agent",rt=!1,It=null,te=null,Ue=new Map,An=(vt=this.config.iterationDisplay)!=null?vt:"separate";for(pt=()=>{var S,ne,Ee,Ne,Ie,Oe,Je,lt,Rt,de,B,ye,_e,wt,Ze,Dt,Et,yt,Pt,Yt,_t,Bn,Ut,Dn,Qn,bn,Ln,Yn,no,Ct,Cr,Ar,Or,dr,mt,Io,Sr,Ro,Pn,is,ro,Fr,oo,so,Wo,Ho,ao,xt,Nn,On,Sn,At,Zn,er,Fn,io,_r,lo,_n,Wt,Tn,tr,co,$r,po,ve,In,Tr,gt,sn,an,Er,Us,jr,Bo,Mr,j,ls,kr,Lr,Ur,Pr,pr,cs,Da,$n,jn,ur,mr,Do,qr,xn,Ir,ds,No,ps,Na,us,Oa,ms,ut,qs,nr,Rn,Fa;for(let gs=0;gs<X.length;gs++){let nt=X[gs].payloadType,w=X[gs].payload;if(!rt&&ke!=="flow"&&typeof w.stepType=="string"&&(ke="flow"),nt==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q),he(V,q,"reasoning");continue}let J=(S=Ae(w,!0))!=null?S:`reason-${l()}`,be=Le(J);be.reasoning=(ne=be.reasoning)!=null?ne:{id:J,status:"streaming",chunks:[]},be.reasoning.startedAt=(Ne=be.reasoning.startedAt)!=null?Ne:Q((Ee=w.startedAt)!=null?Ee:w.timestamp),be.reasoning.completedAt=void 0,be.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(be.reasoning.scope=w.scope),be.streaming=!0,be.reasoning.status="streaming",g(be)}else if(nt==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let $e=k.get(V),ft=(Je=(Oe=(Ie=w.reasoningText)!=null?Ie:w.text)!=null?Oe:w.delta)!=null?Je:"";ft&&w.hidden!==!0&&$e.reasoning&&($e.reasoning.chunks.push(String(ft)),g($e));continue}let q=(Rt=(lt=Ae(w,!1))!=null?lt:Ae(w,!0))!=null?Rt:`reason-${l()}`,J=Le(q);J.reasoning=(de=J.reasoning)!=null?de:{id:q,status:"streaming",chunks:[]},J.reasoning.startedAt=(ye=J.reasoning.startedAt)!=null?ye:Q((B=w.startedAt)!=null?B:w.timestamp);let be=(Ze=(wt=(_e=w.reasoningText)!=null?_e:w.text)!=null?wt:w.delta)!=null?Ze:"";if(be&&w.hidden!==!0){let $e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if($e!==void 0){let ft=fe(q,$e,String(be));J.reasoning.chunks=[ft]}else J.reasoning.chunks.push(String(be))}if(J.reasoning.status=w.done?"complete":"streaming",w.done){J.reasoning.completedAt=Q((Dt=w.completedAt)!=null?Dt:w.timestamp);let $e=(Et=J.reasoning.startedAt)!=null?Et:Date.now();J.reasoning.durationMs=Math.max(0,((yt=J.reasoning.completedAt)!=null?yt:Date.now())-$e)}J.streaming=J.reasoning.status!=="complete",g(J)}else if(nt==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let ft=k.get(V);if(ft.reasoning){let at=typeof w.text=="string"?w.text:"";at&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(at),ft.reasoning.status="complete",ft.streaming=!1,g(ft)}L.delete(V),k.delete(V);continue}let q=(Yt=(Pt=Ae(w,!1))!=null?Pt:Ae(w,!0))!=null?Yt:`reason-${l()}`,J=typeof w.text=="string"?w.text:"";!C.get(q)&&(J||w.scope==="loop")&&Le(q);let be=C.get(q);if(be!=null&&be.reasoning){(w.scope==="loop"||w.scope==="turn")&&(be.reasoning.scope=w.scope),J&&be.reasoning.chunks.length===0&&be.reasoning.chunks.push(J),be.reasoning.status="complete",be.reasoning.completedAt=Q((_t=w.completedAt)!=null?_t:w.timestamp);let ft=(Bn=be.reasoning.startedAt)!=null?Bn:Date.now();be.reasoning.durationMs=Math.max(0,((Ut=be.reasoning.completedAt)!=null?Ut:Date.now())-ft),be.streaming=!1,g(be)}let $e=F(w);$e&&_.byStep.delete($e)}else if(nt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Se=w.iteration);let V=(Qn=(Dn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Dn:Be(w,!0))!=null?Qn:`tool-${l()}`,q=(bn=w.toolName)!=null?bn:w.name;if(xe(q)){Ce.add(V);continue}oe(O(w),V);let J=K(V),be=(Ln=J.toolCall)!=null?Ln:{id:V,status:"pending"};be.name=q!=null?q:be.name,be.status="running",w.parameters!==void 0?be.args=w.parameters:w.args!==void 0&&(be.args=w.args),be.startedAt=(no=be.startedAt)!=null?no:Q((Yn=w.startedAt)!=null?Yn:w.timestamp),be.completedAt=void 0,be.durationMs=void 0,J.toolCall=be,J.streaming=!0,w.executionId&&(J.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(J)}else if(nt==="tool_output_delta"){let V=(Cr=(Ct=Be(w,!1))!=null?Ct:Be(w,!0))!=null?Cr:`tool-${l()}`;if(Ce.has(V))continue;let q=K(V),J=(Ar=q.toolCall)!=null?Ar:{id:V,status:"running"};J.startedAt=(dr=J.startedAt)!=null?dr:Q((Or=w.startedAt)!=null?Or:w.timestamp);let be=(Sr=(Io=(mt=w.text)!=null?mt:w.delta)!=null?Io:w.message)!=null?Sr:"";be&&(J.chunks=(Ro=J.chunks)!=null?Ro:[],J.chunks.push(String(be))),J.status="running",q.toolCall=J,q.streaming=!0;let $e=w.agentContext;($e||w.executionId)&&(q.agentMetadata=(ro=q.agentMetadata)!=null?ro:{executionId:(Pn=$e==null?void 0:$e.executionId)!=null?Pn:w.executionId,iteration:(is=$e==null?void 0:$e.iteration)!=null?is:w.iteration}),g(q)}else if(nt==="tool_complete"){let V=(oo=(Fr=Be(w,!1))!=null?Fr:Be(w,!0))!=null?oo:`tool-${l()}`;if(Ce.has(V)){Ce.delete(V);continue}let q=K(V),J=(so=q.toolCall)!=null?so:{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=Q((Wo=w.completedAt)!=null?Wo:w.timestamp);let be=(Ho=w.duration)!=null?Ho:w.executionTime;if(typeof be=="number")J.durationMs=be;else{let at=(ao=J.startedAt)!=null?ao:Date.now();J.durationMs=Math.max(0,((xt=J.completedAt)!=null?xt:Date.now())-at)}q.toolCall=J,q.streaming=!1;let $e=w.agentContext;($e||w.executionId)&&(q.agentMetadata=(Sn=q.agentMetadata)!=null?Sn:{executionId:(Nn=$e==null?void 0:$e.executionId)!=null?Nn:w.executionId,iteration:(On=$e==null?void 0:$e.iteration)!=null?On:w.iteration}),g(q);let ft=O(w);ft&&U.byCall.delete(ft)}else if(nt==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(At=V!=null?V:w.toolId)!=null?At:`local-${l()}`,J=K(q),be=w.toolName,$e=w.origin==="webmcp"&&!yo(be)?`webmcp:${be}`:be,ft=yo($e),at=(Zn=J.toolCall)!=null?Zn:{id:q,status:"pending"};at.name=$e,at.args=w.parameters,at.status=ft?"running":"complete",at.chunks=(er=at.chunks)!=null?er:[],at.startedAt=(_r=at.startedAt)!=null?_r:Q((io=(Fn=w.startedAt)!=null?Fn:w.timestamp)!=null?io:w.awaitedAt),ft?(at.completedAt=void 0,at.duration=void 0,at.durationMs=void 0):at.completedAt=(lo=at.completedAt)!=null?lo:at.startedAt,J.toolCall=at,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(Wt=w.executionId)!=null?Wt:(_n=J.agentMetadata)==null?void 0:_n.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(J)}else if(nt==="text_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q);continue}let J=f;J&&(ke==="flow"?(Qe(J),tt=J):(J.streaming=!1,g(J)),f=null),E=typeof w.id=="string"?w.id:E,P=""}else if(nt==="text_delta"){let V=typeof w.id=="string"?w.id:null,q=V?L.get(V):void 0;if(V&&q){let be=typeof w.delta=="string"?w.delta:"",$e=((Tn=I.get(V))!=null?Tn:"")+be;if(I.set(V,$e),$e.trim()==="")continue;let ft=he(V,q);ft.agentMetadata={...ft.agentMetadata,executionId:w.executionId,parentToolId:q},jt(ft,$e,be,void 0);continue}if(E=typeof w.id=="string"?w.id:E,ke==="flow"){let be=typeof w.delta=="string"?w.delta:"";if(P+=be,P.trim()==="")continue;let $e=pe();$e.agentMetadata={executionId:w.executionId,iteration:w.iteration},jt($e,P,be,void 0),v=$e;continue}let J=pe();J.content+=(tr=w.delta)!=null?tr:"",J.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:It!=null?It:void 0,agentName:te==null?void 0:te.agentName},v=J,g(J)}else if(nt==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)){let J=k.get(V);J&&Qe(J),L.delete(V),I.delete(V),k.delete(V);continue}let q=f;q&&(ke==="flow"?(Qe(q),tt=q):(((co=q.content)!=null?co:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),f=null),E=null,P=""}else if(nt==="step_complete"){let V=w.stepType,q=w.executionType;if(V==="tool"||q==="context")continue;if(w.success===!1){let J=w.error,be=typeof J=="string"&&J!==""?J:J!=null&&typeof J=="object"&&"message"in J?String(($r=J.message)!=null?$r:"Step failed"):"Step failed";n({type:"error",error:new Error(be)});let $e=f;$e&&$e.streaming&&($e.streaming=!1,g($e)),n({type:"status",status:"idle"});continue}{let J=tt;tt=null;let be=w.stopReason,$e=(po=w.result)==null?void 0:po.response;if(J)be&&(J.stopReason=be),$e!=null?Ke(J,$e):J.streaming!==!1&&(G.delete(J.id),ue.delete(J.id),J.streaming=!1,g(J));else{let ft=$e!=null&&$e!=="";if(ft||be){let at=pe();be&&(at.stopReason=be),ft?Qe(at,$e):(at.streaming=!1,g(at))}}continue}}else if(nt==="execution_start")ke=w.kind==="flow"?"flow":"agent",rt=!0,ke==="agent"&&(te={executionId:w.executionId,agentId:(ve=w.agentId)!=null?ve:"virtual",agentName:(In=w.agentName)!=null?In:"",status:"running",currentIteration:0,maxTurns:(Tr=w.maxTurns)!=null?Tr:1,startedAt:Q(w.startedAt)});else if(nt==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Se;if(V!==Se){if(te&&(te.currentIteration=V),An==="separate"&&V>1){let q=f;q&&(q.streaming=!1,g(q),Ue.set(V-1,q),f=null)}Se=V}It=typeof w.id=="string"?w.id:null,v=null}else if(nt==="tool_input_delta"){let V=(gt=w.toolCallId)!=null?gt:U.lastId;if(V){let q=W.get(V);q!=null&&q.toolCall&&(q.toolCall.chunks=(sn=q.toolCall.chunks)!=null?sn:[],q.toolCall.chunks.push((an=w.delta)!=null?an:""),g(q))}}else{if(nt==="tool_input_complete")continue;if(nt==="turn_complete"){let V=w.stopReason,q=f!=null?f:v;if(V&&q!==null){let J=w.id;(!J||((Er=q.agentMetadata)==null?void 0:Er.turnId)===J)&&(q.stopReason=V,g(q))}It===w.id&&(It=null)}else if(nt==="media_start"){let V=String(w.id);ze.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(nt==="media_delta"){let V=ze.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(nt==="media_complete"){let V=String(w.id),q=ze.get(V);ze.delete(V);let J=(jr=(Us=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Us:q==null?void 0:q.mediaType)!=null?jr:"application/octet-stream",be=typeof w.data=="string"?w.data:void 0,$e=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,ft=null;if(be)ft={type:"media",data:be,mediaType:J};else if($e){let pn=J.toLowerCase();ft={type:pn==="image"||pn.startsWith("image/")?"image-url":"file-url",url:$e,mediaType:J}}let at=(Bo=w.toolCallId)!=null?Bo:q==null?void 0:q.toolCallId,zs=ft?[ft]:[],Wn=[];for(let pn of zs){if(!pn||typeof pn!="object")continue;let un=pn,Oo=typeof un.type=="string"?un.type:void 0,zr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",En=null,hn="";if(Oo==="media"){let Un=typeof un.data=="string"?un.data:void 0;if(!Un)continue;hn=zr.length>0?zr:"application/octet-stream",En=`data:${hn};base64,${Un}`}else if(Oo==="image-url"){let Un=typeof un.url=="string"?un.url:void 0;if(!Un)continue;hn=zr,En=Un}else if(Oo==="file-url"){let Un=typeof un.url=="string"?un.url:void 0;if(!Un)continue;hn=zr,En=Un}else continue;if(En)if(Oo==="image-url"||hn.startsWith("image/"))Wn.push({type:"image",image:En,...hn.includes("/")?{mimeType:hn}:{}});else if(hn.startsWith("audio/"))Wn.push({type:"audio",audio:En,mimeType:hn});else if(hn.startsWith("video/"))Wn.push({type:"video",video:En,mimeType:hn});else{let Un=hn||"application/octet-stream";Wn.push({type:"file",data:En,mimeType:Un,filename:uy(Un)})}}if(Wn.length>0){let pn=l(),un=at,zr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${pn}`:String(pn)}`,role:"assistant",content:"",contentParts:Wn,createdAt:new Date().toISOString(),streaming:!1,sequence:pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Se}};g(zr);let En=f;En&&(En.streaming=!1,g(En)),f=null,x.current=null}}else if(nt==="execution_complete"){let V=(Mr=w.kind)!=null?Mr:ke;V==="agent"&&te&&(te.status=w.success?"complete":"error",te.completedAt=Q(w.completedAt),te.stopReason=w.stopReason);let q=f;q&&(V==="flow"&&q.streaming!==!1?Qe(q):(q.streaming=!1,g(q)),f=null),E=null,P="",tt=null,n({type:"status",status:"idle"})}else if(nt==="execution_error"){let V=typeof w.error=="string"?w.error:(ls=(j=w.error)==null?void 0:j.message)!=null?ls:"Execution error";n({type:"error",error:new Error(V)})}else if(nt!=="ping"){if(nt==="approval_start"){let V=(kr=w.approvalId)!=null?kr:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Lr=te==null?void 0:te.agentId)!=null?Lr:"virtual",executionId:(Pr=(Ur=w.executionId)!=null?Ur:te==null?void 0:te.executionId)!=null?Pr:"",toolName:(pr=w.toolName)!=null?pr:"",toolType:w.toolType,description:(Da=w.description)!=null?Da:`Execute ${(cs=w.toolName)!=null?cs:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(nt==="step_await"&&w.awaitReason==="approval_required"){let V=($n=w.approvalId)!=null?$n:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(jn=te==null?void 0:te.agentId)!=null?jn:"virtual",executionId:(mr=(ur=w.executionId)!=null?ur:te==null?void 0:te.executionId)!=null?mr:"",toolName:(Do=w.toolName)!=null?Do:"",toolType:w.toolType,description:(xn=w.description)!=null?xn:`Execute ${(qr=w.toolName)!=null?qr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(nt==="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:l(),approval:{id:V,status:(Ir=w.decision)!=null?Ir:"approved",agentId:(ds=te==null?void 0:te.agentId)!=null?ds:"virtual",executionId:(ps=(No=w.executionId)!=null?No:te==null?void 0:te.executionId)!=null?ps:"",toolName:(Na=w.toolName)!=null?Na:"",description:(us=w.description)!=null?us:"",resolvedAt:Date.now()}};g(J)}}else if(nt==="artifact_start"||nt==="artifact_delta"||nt==="artifact_update"||nt==="artifact_complete"){if(nt==="artifact_start"){let V=w.artifactType,q=String(w.id),J=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:V,title:J,component:typeof w.component=="string"?w.component:void 0}),se.set(q,{markdown:"",title:J}),!ae.has(q)){ae.add(q);let be={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:J,artifactType:V,status:"streaming"}})};ce.set(q,be),g(be)}}else if(nt==="artifact_delta"){let V=String(w.id),q=typeof w.delta=="string"?w.delta:String((Oa=w.delta)!=null?Oa:"");n({type:"artifact_delta",id:V,artDelta:q});let J=se.get(V);J&&(J.markdown+=q)}else if(nt==="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(nt==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let q=ce.get(V);if(q){q.streaming=!1;try{let J=JSON.parse((ms=q.rawContent)!=null?ms:"{}");if(J.props){J.props.status="complete";let be=se.get(V);be!=null&&be.markdown&&(J.props.markdown=be.markdown)}q.rawContent=JSON.stringify(J)}catch{}se.delete(V),g(q),ce.delete(V)}}}else if(nt==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let q=String((ut=V.id)!=null?ut:`msg-${l()}`),J=V.role,$e={id:q,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:l()};if(g($e),$e.rawContent)try{let ft=JSON.parse($e.rawContent),at=(qs=ft==null?void 0:ft.props)==null?void 0:qs.artifactId;typeof at=="string"&&ae.add(at)}catch{}f=null,x.current=null,G.delete(q),ue.delete(q)}else if(nt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((nr=w.error)==null?void 0:nr.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(nt==="step_error"||nt==="dispatch_error"||nt==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(nt==="dispatch_error"){let q=(Rn=w.message)!=null?Rn:w.error;q!=null&&q!==""&&(V=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?V=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(V=new Error(String((Fa=q.message)!=null?Fa:q)))}if(V){n({type:"error",error:V});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}X.length=0};;){let{done:S,value:ne}=await o.read();if(S)break;a+=s.decode(ne,{stream:!0});let Ee=a.split(`
|
|
12
12
|
|
|
13
|
-
`);a=(
|
|
14
|
-
`),Ne="message",Je="";for(let xt of Pe)xt.startsWith("event:")?Ne=xt.replace("event:","").trim():xt.startsWith("data:")&&(Je+=xt.replace("data:","").trim());if(!Je)continue;let lt;try{lt=JSON.parse(Je)}catch(xt){n({type:"error",error:xt instanceof Error?xt:new Error("Failed to parse chat stream payload")});continue}let It=Ne!=="message"?Ne:(Or=lt.type)!=null?Or:"message";if((wr=this.onSSEEvent)==null||wr.call(this,It,lt),this.parseSSEEvent){x.current=f;let xt=await this.handleCustomSSEEvent(lt,n,x,g,l,M);if(x.current&&x.current!==f&&(f=x.current),xt)continue}J.push({payloadType:It,payload:lt}),Ve()}}Ve()}};function Om(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ks(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var li="[Image]";function Fm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function _m(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function $m(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function jm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ma(e){return{type:"text",text:e}}function Um(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function qm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let 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 zm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Vm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fy=["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=[...Vm,...fy];function hy(e){return Vm.includes(e)||e.startsWith("image/")}function ci(e){return hy(e.type)}async function Km(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ci(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 Gm(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 yy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Jm(e,t){let n=yy(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"}Pl();var Xm=16e3,by=24e3,xy=4096,vy=1380533830;function wy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vy?new Uint8Array(e,44):new Uint8Array(e)}function Cy(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 ga=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 l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Xm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ls(by);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Cy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let M=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}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(xy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.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=wy(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 Qo=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 Ao(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ga(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(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 di(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Ao({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ao({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Ao({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function fa(e){try{return di(e),!0}catch{return!1}}function Ps(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 So=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):Ps(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 l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.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 Yo=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 Il(e){if(!e)return"";let t=Ay(e);return Qm(t!==null?t:e)}function Ay(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 Qm(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);a=(yn=Ee.pop())!=null?yn:"";for(let Ne of Ee){let Ie=Ne.split(`
|
|
14
|
+
`),Oe="message",Je="";for(let de of Ie)de.startsWith("event:")?Oe=de.replace("event:","").trim():de.startsWith("data:")&&(Je+=de.replace("data:","").trim());if(!Je)continue;let lt;try{lt=JSON.parse(Je)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let Rt=Oe!=="message"?Oe:(vr=lt.type)!=null?vr:"message";if((wr=this.onSSEEvent)==null||wr.call(this,Rt,lt),this.parseSSEEvent){x.current=f;let de=await this.handleCustomSSEEvent(lt,n,x,g,l,M);if(x.current&&x.current!==f&&(f=x.current),de)continue}X.push({payloadType:Rt,payload:lt}),pt()}}pt()}};function Om(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ks(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var li="[Image]";function Fm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function _m(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function $m(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function jm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ma(e){return{type:"text",text:e}}function Um(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function qm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let 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 zm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Vm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fy=["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"],Qr=[...Vm,...fy];function hy(e){return Vm.includes(e)||e.startsWith("image/")}function ci(e){return hy(e.type)}async function Km(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ci(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 Gm(e,t=Qr,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 yy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Jm(e,t){let n=yy(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"}Pl();var Xm=16e3,by=24e3,xy=4096,vy=1380533830;function wy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vy?new Uint8Array(e,44):new Uint8Array(e)}function Cy(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 ga=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 l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Xm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ls(by);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Cy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let M=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}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(xy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.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=wy(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 Qo=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 Ao(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ga(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(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 di(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Ao({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ao({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Ao({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function fa(e){try{return di(e),!0}catch{return!1}}function Ps(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 So=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):Ps(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 l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.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 Yo=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 Il(e){if(!e)return"";let t=Ay(e);return Qm(t!==null?t:e)}function Ay(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 Qm(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
16
16
|
`),t.trim()}var ng=null;var Rl=()=>ng?ng():Promise.resolve().then(()=>(tg(),eg));var Ey=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function My(e,t){return Ey.some(n=>e[n]!==t[n])}function rg(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]}),og=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,sg=e=>yo(e)||e===xr,Is=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Yo(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(yo(g.name)||g.name===xr&&((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&&f&&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==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.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 Jo(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,l;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=(l=(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?l:this.config.agentId;!n||!r||!this.config.clientToken||Rl().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 fa((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=So.isSupported()?new So({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(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,g=t.browserFallback!==!1;if(l&&p&&u)return Rl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:v})=>{let x=new f({host:l,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&n?new v(x,n,{onFallback:M=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${M.message}`)}):x});if(g&&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=Ao(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,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){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:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,l;(l=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||l.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,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(d=this.callbacks).onVoiceStatusChanged)==null||l.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,l,p,u,g,f;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:(l=(d=t.runtype)==null?void 0:d.host)!=null?l: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:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.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(!My(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 Jo(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:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:a!=null?a:n==="user"?ks():n==="assistant"?Xo():`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:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,x={id:d!=null?d:o==="user"?ks():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(x)}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,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...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 l,p,u,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=ks(),s=Xo(),a={id:o,role:"user",content:r||li,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(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let M=rg(v,this.config.errorMessage);if(M){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Xo();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(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=rg(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var 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,g,f,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.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,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let M=null;if(x instanceof Response){if(!x.ok){let E=await x.json().catch(()=>null);throw new Error((g=E==null?void 0:E.error)!=null?g:`Approval request failed: ${x.status}`)}M=x.body}else x instanceof ReadableStream&&(M=x);M?await this.connectStream(M,{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(x){let M=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(v=(f=this.callbacks).onError)==null||v.call(f,x instanceof Error?x:new Error(String(x)))}}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,g,f,v,x,M,E,P,L,k,I;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=(g=t.toolCall)==null?void 0:g.name;if(!o||!s){(v=(f=this.callbacks).onError)==null||v.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(x=t.toolCall)==null?void 0:x.args,W=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(W.length===1){let _=typeof((M=W[0])==null?void 0:M.question)=="string"?W[0].question:"";_&&(a={[_]: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,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([W,_])=>`${W}: ${Array.isArray(_)?_.join(", "):_}`).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:{};l.forEach((W,_)=>{let U=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!U)return;let H=C[U],F=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let W=await C.json().catch(()=>null);throw new Error((L=W==null?void 0:W.error)!=null?L:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let W=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(I=(k=this.callbacks).onError)==null||I.call(k,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)!==xr)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,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var I,C,W,_,U,H,F;let f=(I=g.toolCall)==null?void 0:I.name,v=(C=g.toolCall)==null?void 0:C.id;if(!f||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let M=this.markWebMcpToolRunning(g),E=(_=(W=g.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?_:f;if(f===xr)return{dedupeKey:x,resumeKey:E,output:Sl(),toolMessage:g,startedAt:M,completedAt:Date.now()};let P=new AbortController;this.webMcpResolveControllers.add(P),o.push(P);let L=this.client.executeWebMcpToolCall(f,(U=g.toolCall)==null?void 0:U.args,P.signal),k;if(!L)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await L}catch(O){let ee=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return ee||(F=(H=this.callbacks).onError)==null||F.call(H,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(g,ha(ee?"Aborted by cancel()":og(O)),M),this.webMcpInflightKeys.delete(x),null}return P.signal.aborted?(this.markWebMcpToolComplete(g,ha("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:E,output:k,toolMessage:g,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let f=await this.client.resumeFlow(t,g,{signal:s.signal});if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${f.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===xr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ha("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,M,E,P,L,k,I,C,W,_,U;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(M=t.toolCall)==null?void 0:M.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 H=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(H)||this.webMcpResolvedKeys.has(H))return;this.webMcpInflightKeys.add(H);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(H)}catch(F){(k=(L=this.callbacks).onError)==null||k.call(L,F instanceof Error?F:new Error(String(F)))}finally{this.webMcpInflightKeys.delete(H)}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 l=r===xr,p=(I=t.toolCall)==null?void 0:I.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let H;if(l?H=Sl():u?H=await u:H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ha("Aborted by cancel()"),a);return}let F=(W=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?W:r;g="resume",await this.resumeWithToolOutput(n,F,H,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,H,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(H){let F=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));(g==="execute"||F||d.aborted)&&this.markWebMcpToolComplete(t,ha(F||d.aborted?"Aborted by cancel()":og(H)),a),F||(U=(_=this.callbacks).onError)==null||U.call(_,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,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.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var 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.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()}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=Il(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ps(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=Il(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,g,f,v,x,M,E,P,L,k,I,C,W,_;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={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let U=o.approval,H=n.approval;a.approval={...U,...H,executionId:H.executionId||U.executionId,toolName:H.toolName||U.toolName,description:H.description||U.description,toolType:(f=H.toolType)!=null?f:U.toolType,reason:(v=H.reason)!=null?v:U.reason,parameters:(x=H.parameters)!=null?x:U.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(E=n.agentMetadata)==null?void 0:E.executionId,l=(P=n.toolCall)==null?void 0:P.id;if(i&&sg(i)&&d&&l&&((L=n.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let U=`${d}:${l}`,H=this.webMcpInflightKeys.has(U),F=this.webMcpResolvedKeys.has(U),O=(k=o.toolCall)==null?void 0:k.name,ee=((I=o.agentMetadata)==null?void 0:I.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&O!==void 0&&sg(O)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(H||F||ee)&&(a.agentMetadata={...(_=a.agentMetadata)!=null?_:{},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,l;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=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var A=require("lucide"),ky={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},ge=(e,t=24,n="currentColor",r=2)=>{let o=ky[e];return o?Ly(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 Ly(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(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var mi={allowedTypes:Yr,maxFileSize:10*1024*1024,maxFiles:4};function Py(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Iy(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 Zo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:mi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:mi.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:mi.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:mi.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 l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Gm(l,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,l,u);continue}try{let u=await Km(l),g=ci(l)?URL.createObjectURL(l):null,f={id:Py(),file:l,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}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=ci(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=Iy(t.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=Jm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),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=ge("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 ag=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ya(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];ag(s)&&ag(o)?n[r]=ya(s,o):n[r]=o}return n}var Xn="min(440px, calc(100vw - 24px))",gi="440px",Ry={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Xn,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:Ry,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ig(e,t){if(!(!e&&!t))return e?t?ya(e,t):e:t}function fi(e){var t,n,r,o,s,a,i,d,l,p,u,g,f,v,x,M,E,P,L,k,I;return e?{...Bt,...e,theme:ig(Bt.theme,e.theme),darkTheme:ig(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 pe,ie,ae,He,Fe,K,G,we,X,de;let C=(pe=Bt.features)==null?void 0:pe.artifacts,W=(ie=e.features)==null?void 0:ie.artifacts,_=(ae=Bt.features)==null?void 0:ae.scrollToBottom,U=(He=e.features)==null?void 0:He.scrollToBottom,H=(Fe=Bt.features)==null?void 0:Fe.scrollBehavior,F=(K=e.features)==null?void 0:K.scrollBehavior,O=(G=Bt.features)==null?void 0:G.streamAnimation,ee=(we=e.features)==null?void 0:we.streamAnimation,Ee=(X=Bt.features)==null?void 0:X.askUserQuestion,ue=(de=e.features)==null?void 0:de.askUserQuestion,te=C===void 0&&W===void 0?void 0:{...C,...W,layout:{...C==null?void 0:C.layout,...W==null?void 0:W.layout}},ve=_===void 0&&U===void 0?void 0:{..._,...U},ke=H===void 0&&F===void 0?void 0:{...H,...F},se=O===void 0&&ee===void 0?void 0:{...O,...ee},xe=Ee===void 0&&ue===void 0?void 0:{...Ee,...ue,styles:{...Ee==null?void 0:Ee.styles,...ue==null?void 0:ue.styles}};return{...Bt.features,...e.features,...ve!==void 0?{scrollToBottom:ve}:{},...ke!==void 0?{scrollBehavior:ke}:{},...te!==void 0?{artifacts:te}:{},...se!==void 0?{streamAnimation:se}:{},...xe!==void 0?{askUserQuestion:xe}:{}}})(),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,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(x=(v=Bt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(M=e.layout)==null?void 0:M.messages)==null?void 0:E.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(L=e.layout)==null?void 0:L.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(k=Bt.markdown)==null?void 0:k.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var Wl={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"}},Hl={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"}},Bl={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:Xn,maxWidth:gi,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 Rs(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."))?Rs(e,r):r}function hi(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=Rs(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 Dl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function lg(e,t){let n={...e};for(let[r,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]=lg(s,o):n[r]=o}return n}function Wy(e,t){return t?lg(e,t):e}function Ws(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,M;let n={palette:Wl,semantic:Hl,components:Bl},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,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:Wy(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Dl(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 yi(e){var x,M,E,P,L,k,I,C,W,_,U,H,F,O,ee,Ee,ue,te,ve,ke,se,xe,pe,ie,ae,He,Fe,K,G,we,X,de,We,fe,Ge,nt,Pt,Ze,$e,J,Ve,ze,Ce,Se,rt,_t,re,je,yn,Dt,Yt,Or,wr,S,ne,Me,De,Pe,Ne,Je,lt,It,xt,B,Y,Te,ct,Ye,Ut,bn,vt,wt,Rt,Ct,pn,$t,On,Tn,En,vn,Mn,dr,At,Cr,Ar,Fr,pr,mt,Io,Sr,Ro,Wn,is,ro,_r,oo,so,Wo,Ho,ao,bt,Fn,_n,kn,St,Zn,er,$n,io,$r,lo,jn,Wt,Ln,tr,co,jr,po;let t=hi(e),n={};for(let[ye,Hn]of Object.entries(t)){let Tr=ye.replace(/\./g,"-");n[`--persona-${Tr}`]=Hn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M: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"]=(L=n["--persona-semantic-colors-background"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(k=n["--persona-semantic-colors-container"])!=null?k:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(I=n["--persona-semantic-colors-text"])!=null?I: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"]=(W=n["--persona-semantic-colors-text-inverse"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(_=n["--persona-semantic-colors-border"])!=null?_: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"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H: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"]=(O=n["--persona-components-voice-processing-icon"])!=null?O: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"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(ue=n["--persona-components-approval-requested-border"])!=null?ue: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"]=(ve=n["--persona-components-approval-requested-shadow"])!=null?ve:"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"]=(ke=n["--persona-components-approval-approve-background"])!=null?ke:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(se=n["--persona-components-approval-deny-background"])!=null?se:n["--persona-container"],n["--persona-attachment-image-bg"]=(xe=n["--persona-components-attachment-image-background"])!=null?xe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(pe=n["--persona-components-attachment-image-border"])!=null?pe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ie=n["--persona-semantic-typography-fontFamily"])!=null?ie:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(He=n["--persona-semantic-typography-fontWeight"])!=null?He:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Fe=n["--persona-semantic-typography-lineHeight"])!=null?Fe: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"]=(G=n["--persona-palette-radius-md"])!=null?G:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(de=n["--persona-palette-radius-full"])!=null?de:"9999px",n["--persona-launcher-radius"]=(fe=(We=n["--persona-components-launcher-borderRadius"])!=null?We:n["--persona-palette-radius-full"])!=null?fe:"9999px",n["--persona-launcher-bg"]=(Ge=n["--persona-components-launcher-background"])!=null?Ge:n["--persona-primary"],n["--persona-launcher-fg"]=(nt=n["--persona-components-launcher-foreground"])!=null?nt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Pt=n["--persona-components-launcher-border"])!=null?Pt:n["--persona-border"],n["--persona-button-primary-bg"]=(Ze=n["--persona-components-button-primary-background"])!=null?Ze:n["--persona-primary"],n["--persona-button-primary-fg"]=($e=n["--persona-components-button-primary-foreground"])!=null?$e:n["--persona-text-inverse"],n["--persona-button-radius"]=(Ve=(J=n["--persona-components-button-primary-borderRadius"])!=null?J:n["--persona-palette-radius-full"])!=null?Ve:"9999px",n["--persona-panel-radius"]=(Ce=(ze=n["--persona-components-panel-borderRadius"])!=null?ze:n["--persona-radius-xl"])!=null?Ce:"0.75rem",n["--persona-panel-border"]=(Se=n["--persona-components-panel-border"])!=null?Se:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(_t=(rt=n["--persona-components-panel-shadow"])!=null?rt:n["--persona-palette-shadows-xl"])!=null?_t:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(re=n["--persona-components-launcher-shadow"])!=null?re:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(yn=(je=n["--persona-components-input-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?yn:"0.5rem",n["--persona-message-user-radius"]=(Yt=(Dt=n["--persona-components-message-user-borderRadius"])!=null?Dt:n["--persona-radius-lg"])!=null?Yt:"0.5rem",n["--persona-message-assistant-radius"]=(wr=(Or=n["--persona-components-message-assistant-borderRadius"])!=null?Or:n["--persona-radius-lg"])!=null?wr:"0.5rem",n["--persona-header-bg"]=(S=n["--persona-components-header-background"])!=null?S:n["--persona-surface"],n["--persona-header-border"]=(ne=n["--persona-components-header-border"])!=null?ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Me=n["--persona-components-header-iconBackground"])!=null?Me:n["--persona-primary"],n["--persona-header-icon-fg"]=(De=n["--persona-components-header-iconForeground"])!=null?De:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pe=n["--persona-components-header-titleForeground"])!=null?Pe:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Ne=n["--persona-components-header-subtitleForeground"])!=null?Ne:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Je=n["--persona-components-header-actionIconForeground"])!=null?Je:n["--persona-muted"];let r=(lt=e.components)==null?void 0:lt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(It=e.components)==null?void 0:It.introCard;n["--persona-intro-card-bg"]=(xt=n["--persona-components-introCard-background"])!=null?xt:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(Y=n["--persona-components-introCard-padding"])!=null?Y:"1.5rem",n["--persona-intro-card-shadow"]=(ct=(Te=o==null?void 0:o.shadow)!=null?Te:n["--persona-components-introCard-shadow"])!=null?ct:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ye=n["--persona-components-input-background"])!=null?Ye:n["--persona-surface"],n["--persona-input-placeholder"]=(Ut=n["--persona-components-input-placeholder"])!=null?Ut:n["--persona-text-muted"],n["--persona-message-user-bg"]=(bn=n["--persona-components-message-user-background"])!=null?bn: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"]=(Rt=n["--persona-components-message-assistant-background"])!=null?Rt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ct=n["--persona-components-message-assistant-text"])!=null?Ct:n["--persona-text"],n["--persona-message-assistant-border"]=(pn=n["--persona-components-message-assistant-border"])!=null?pn:n["--persona-border"],n["--persona-message-assistant-shadow"]=($t=n["--persona-components-message-assistant-shadow"])!=null?$t:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Tn=(On=n["--persona-components-scrollToBottom-background"])!=null?On:n["--persona-button-primary-bg"])!=null?Tn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(En=n["--persona-components-scrollToBottom-foreground"])!=null?En:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Mn=n["--persona-components-scrollToBottom-border"])!=null?Mn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(dr=n["--persona-components-scrollToBottom-size"])!=null?dr:"40px",n["--persona-scroll-to-bottom-radius"]=(Ar=(Cr=(At=n["--persona-components-scrollToBottom-borderRadius"])!=null?At:n["--persona-button-radius"])!=null?Cr:n["--persona-radius-full"])!=null?Ar:"9999px",n["--persona-scroll-to-bottom-shadow"]=(pr=(Fr=n["--persona-components-scrollToBottom-shadow"])!=null?Fr:n["--persona-palette-shadows-sm"])!=null?pr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(mt=n["--persona-components-scrollToBottom-padding"])!=null?mt:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Io=n["--persona-components-scrollToBottom-gap"])!=null?Io:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Ro=(Sr=n["--persona-components-scrollToBottom-fontSize"])!=null?Sr:n["--persona-palette-typography-fontSize-sm"])!=null?Ro:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Wn=n["--persona-components-scrollToBottom-iconSize"])!=null?Wn:"14px",n["--persona-tool-bubble-shadow"]=(is=n["--persona-components-toolBubble-shadow"])!=null?is:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(ro=n["--persona-components-reasoningBubble-shadow"])!=null?ro:"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"]=(oo=n["--persona-components-markdown-inlineCode-background"])!=null?oo:n["--persona-container"],n["--persona-md-inline-code-color"]=(so=n["--persona-components-markdown-inlineCode-foreground"])!=null?so:n["--persona-text"],n["--persona-md-link-color"]=(Ho=(Wo=n["--persona-components-markdown-link-foreground"])!=null?Wo:n["--persona-accent"])!=null?Ho:"#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 l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(ao=n["--persona-components-markdown-codeBlock-background"])!=null?ao:n["--persona-container"],n["--persona-md-code-block-border-color"]=(bt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?bt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Fn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Fn:"inherit",n["--persona-md-table-header-bg"]=(_n=n["--persona-components-markdown-table-headerBackground"])!=null?_n:n["--persona-container"],n["--persona-md-table-border-color"]=(kn=n["--persona-components-markdown-table-borderColor"])!=null?kn:n["--persona-border"],n["--persona-md-hr-color"]=(St=n["--persona-components-markdown-hr-color"])!=null?St:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Zn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Zn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(er=n["--persona-components-markdown-blockquote-background"])!=null?er:"transparent",n["--persona-md-blockquote-text-color"]=($n=n["--persona-components-markdown-blockquote-textColor"])!=null?$n:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(io=n["--persona-components-collapsibleWidget-container"])!=null?io:n["--persona-surface"],n["--cw-surface"]=($r=n["--persona-components-collapsibleWidget-surface"])!=null?$r:n["--persona-surface"],n["--cw-border"]=(lo=n["--persona-components-collapsibleWidget-border"])!=null?lo:n["--persona-border"],n["--persona-message-border"]=(jn=n["--persona-components-message-border"])!=null?jn: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 g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,n["--persona-dropdown-bg"]=(Wt=n["--persona-dropdown-bg"])!=null?Wt:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(Ln=n["--persona-dropdown-border"])!=null?Ln:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(tr=n["--persona-dropdown-shadow"])!=null?tr:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(co=n["--persona-dropdown-radius"])!=null?co:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(jr=n["--persona-dropdown-item-hover-bg"])!=null?jr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(n["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(n["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(n["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(n["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(n["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(n["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let Hn=(po=Rs(e,ye.toolbarBackground))!=null?po:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Hn}}return n}var cg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Hy={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},ba=()=>{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"},By=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ba()},Nl=e=>By(e),Dy=e=>Ws(e),Ny=e=>{var n;let t=Ws(void 0,{validate:!1});return Ws({...e,palette:{...t.palette,colors:{...Hy.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Hs=e=>{let t=Nl(e),n=dg(e==null?void 0:e.theme),r=dg(e==null?void 0:e.darkTheme);return t==="dark"?Ny(ya(n!=null?n:{},r!=null?r:{})):Dy(n)},Oy=e=>yi(e),To=(e,t)=>{let n=Hs(t),r=Oy(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},bi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ba())});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(ba());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var pg=require("idiomorph"),xi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;pg.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:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var ug=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var vi={index:-1,draft:""};function mg(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:{...vi}}}function gg(e,t){var n,r,o,s,a,i,d,l,p,u,g,f,v,x,M,E,P,L,k,I,C,W,_,U,H,F,O,ee,Ee,ue,te,ve,ke,se,xe,pe,ie,ae;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=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(M=(x=e.toolCall)==null?void 0:x.name)!=null?M:"",(L=(P=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:P.length)!=null?L:0,(W=(C=(I=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?W:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:(U=e.toolCall)!=null&&U.args?JSON.stringify(e.toolCall.args).length:0,(O=(F=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:F.length)!=null?O:0,(te=(ue=(Ee=(ee=e.reasoning)==null?void 0:ee.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?te:0,(xe=(se=(ke=(ve=e.reasoning)==null?void 0:ve.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:se.slice(-32))!=null?xe:"",(ie=(pe=e.contentParts)==null?void 0:pe.length)!=null?ie:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function fg(){return new Map}function hg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function yg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function bg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function wi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Zr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function es(e,t){return Zr(e)-e.scrollTop<=t}function Ci(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||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 Ai(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 xg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function vg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function wg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var An={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Sn=1e5,Eo=Sn+1;var xa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Fy=["pre","code","a","script","style"],Si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:xa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:xa.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:xa.speed,duration:(o=e==null?void 0:e.duration)!=null?o:xa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:xa.buffer}},Ag=[{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"}],va=new Map;for(let e of Ag)va.set(e.name,e);var Sg=e=>{va.set(e.name,e)},Tg=e=>{Ag.some(t=>t.name===e)||va.delete(e)},Eg=()=>Array.from(va.keys()),wa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=va.get(e))!=null?r:null},Ti=(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},_y=(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},$y=(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},Ol=/\s/,jy=(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},Uy=(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(Ol.test(s[i])){let l=i;for(;l<s.length&&Ol.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Ol.test(s[p]);)l.appendChild(_y(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},qy=(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 l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild($y(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},Ca=(e,t,n,r)=>{var u,g;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:Fy).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)jy(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Uy:qy;for(let f of i)p(f,n,l);return o.innerHTML},Ei=(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},Aa=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Cg=new WeakMap,zy=(e,t)=>{var s;if(!e.styles)return;let n=Cg.get(t);if(n||(n=new Set,Cg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let 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)},Fl=new WeakMap,Vy=(e,t)=>{if(!e.onAttach)return;let n=Fl.get(t);if(n||(n=new Map,Fl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Mg=e=>{let t=Fl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},_l=(e,t)=>{zy(e,t),Vy(e,t)};function $l(e,t=Sn){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 Sa=0,Mo=null;function jl(e=document){var n;if(Sa++,Sa===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Mo={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,Sa=Math.max(0,Sa-1),Sa===0&&Mo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Mo.originalOverflow,o.style.position=Mo.originalPosition,o.style.top=Mo.originalTop,o.style.width=Mo.originalWidth,s.scrollTo(0,Mo.scrollY),Mo=null}}}var Ta={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"},ko=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Qn=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:Ta.side,width:(o=t==null?void 0:t.width)!=null?o:Ta.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ta.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ta.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Ta.maxHeight}};var vr={"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 Ky="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Mi=(e,t={})=>{var M,E,P,L,k,I;let{showClose:n=!0,wrapperClassName:r=Ky,buttonSize:o,iconSize:s="28px"}=t,a=(M=e==null?void 0:e.launcher)!=null?M:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=y("div",r),l=(P=a.closeButtonTooltipText)!=null?P:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0,u=(k=a.closeButtonIconName)!=null?k:"x",g=(I=a.closeButtonIconText)!=null?I:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Et("button",{className:oa("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Rn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=ge(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,W=()=>{if(C)return;let U=v.ownerDocument,H=U.body;if(!H)return;C=Dr(U,"div","persona-clear-chat-tooltip"),C.textContent=l;let F=Dr(U,"div");F.className="persona-clear-chat-tooltip-arrow",C.appendChild(F);let O=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Eo),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",H.appendChild(C)},_=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",_),v.addEventListener("focus",W),v.addEventListener("blur",_),d._cleanupTooltip=()=>{_(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",_),v.removeEventListener("focus",W),v.removeEventListener("blur",_)}}return{button:v,wrapper:d}},Gy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ki=(e,t={})=>{var C,W,_,U,H,F,O,ee,Ee,ue,te,ve,ke;let{wrapperClassName:n=Gy,buttonSize:r,iconSize:o="20px"}=t,a=(W=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?W:{},i=(_=r!=null?r:a.size)!=null?_:"32px",d=(U=a.iconName)!=null?U:"refresh-cw",l=(H=a.iconColor)!=null?H:"",p=(F=a.backgroundColor)!=null?F:"",u=(O=a.borderWidth)!=null?O:"",g=(ee=a.borderColor)!=null?ee:"",f=(Ee=a.borderRadius)!=null?Ee:"",v=(ue=a.paddingX)!=null?ue:"",x=(te=a.paddingY)!=null?te:"",M=(ve=a.tooltipText)!=null?ve:"Clear chat",E=(ke=a.showTooltip)!=null?ke:!0,P=y("div",n),L=!!(u||g),k=Et("button",{className:oa("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!L&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:l||Rn.actionIconColor,backgroundColor:p||void 0,border:L?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),I=ge(d,o,"currentColor",1);if(I&&(I.style.display="block",k.appendChild(I)),P.appendChild(k),E&&M){let se=null,xe=()=>{if(se)return;let ie=k.ownerDocument,ae=ie.body;if(!ae)return;se=Dr(ie,"div","persona-clear-chat-tooltip"),se.textContent=M;let He=Dr(ie,"div");He.className="persona-clear-chat-tooltip-arrow",se.appendChild(He);let Fe=k.getBoundingClientRect();se.style.position="fixed",se.style.zIndex=String(Eo),se.style.left=`${Fe.left+Fe.width/2}px`,se.style.top=`${Fe.top-8}px`,se.style.transform="translate(-50%, -100%)",ae.appendChild(se)},pe=()=>{se&&se.parentNode&&(se.parentNode.removeChild(se),se=null)};P.addEventListener("mouseenter",xe),P.addEventListener("mouseleave",pe),k.addEventListener("focus",xe),k.addEventListener("blur",pe),P._cleanupTooltip=()=>{pe(),P.removeEventListener("mouseenter",xe),P.removeEventListener("mouseleave",pe),k.removeEventListener("focus",xe),k.removeEventListener("blur",pe)}}return{button:k,wrapper:P}};var Rn={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))"},eo=e=>{var I,C,W,_,U,H,F,O,ee,Ee,ue,te,ve,ke,se,xe;let{config:t,showClose:n=!0}=e,r=Et("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=(C=o.headerIconSize)!=null?C:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",i=(_=o.headerIconHidden)!=null?_:!1,d=o.headerIconName,l=Et("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 pe=parseFloat(s)||24,ie=ge(d,pe*.6,"currentColor",1);ie?l.replaceChildren(ie):l.textContent=(H=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?H:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let pe=y("img");pe.src=t.launcher.iconUrl,pe.alt="",pe.className="persona-rounded-xl persona-object-cover",pe.style.height=s,pe.style.width=s,l.replaceChildren(pe)}else l.textContent=(ee=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?ee:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Et("span",{className:"persona-text-base persona-font-semibold",text:(ue=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?ue:"Chat Assistant",style:{color:Rn.titleColor}}),g=Et("span",{className:"persona-text-xs",text:(ve=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?ve:"Here to help you get answers fast",style:{color:Rn.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(ke=o.clearChat)!=null?ke:{},v=(se=f.enabled)!=null?se:!0,x=(xe=f.placement)!=null?xe:"inline",M=null,E=null;if(v){let ie=ki(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=ie.button,E=ie.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:L,wrapper:k}=Mi(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:L,closeButtonWrapper:k,clearChatButton:M,clearChatButtonWrapper:E}},ts=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"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 Lo(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(Eo)):(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 f of t){if(f.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let M=ge(f.icon,16,"currentColor",1.5);M&&v.appendChild(M)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",M=>{M.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}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 l=ge(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Ea(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=ge(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function Ma(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 l(p){a=p,d()}return{element:s,setSelected:l}}function Li(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=ge(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,M;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Lo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Ul=e=>{var r;let t=eo({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 Jy(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=ge(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 l=Lo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ql=e=>{var P,L,k,I,C,W,_,U,H;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,l,p;if(d)l=Li({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Rn.titleColor,p=(k=l.querySelector(".persona-combo-btn-label"))!=null?k:l;else{if(l=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=Rn.titleColor,p.textContent=(I=a.title)!=null?I:"Chat Assistant",l.appendChild(p),Jy(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=o.onTitleClick;l.addEventListener("click",ee=>{ee.target.closest("button")||O()}),l.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),O())})}let F=o==null?void 0:o.titleRowHover;F&&(l.style.borderRadius=(W=F.borderRadius)!=null?W:"10px",l.style.padding=(_=F.padding)!=null?_:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var O,ee;l.style.backgroundColor=(O=F.background)!=null?O:"",l.style.borderColor=(ee=F.border)!=null?ee:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(U=a.closeButtonSize)!=null?U:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Rn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=ge(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let M=y("div");M.style.display="none";let E=y("span");return E.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:E,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Pi={default:Ul,minimal:ql},zl=e=>{var t;return(t=Pi[e])!=null?t:Pi.default},Bs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=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"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,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 Ii=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}},Ri=e=>{var I,C,W,_,U,H,F,O,ee,Ee,ue,te;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(C=t.useIcon)!=null?C:!1,r=(W=t.iconText)!=null?W:"\u2191",o=t.iconName,s=(_=t.stopIconName)!=null?_:"square",a=(U=t.tooltipText)!=null?U:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(O=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?O:"Send",l=(Ee=(ee=e==null?void 0:e.copy)==null?void 0:ee.stopButtonLabel)!=null?Ee:"Stop",p=(ue=t.showTooltip)!=null?ue:!1,u=(te=t.size)!=null?te:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=Et("button",{className:oa("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,E=null;if(n){let ve=parseFloat(u)||24,ke=(f==null?void 0:f.trim())||"currentColor";o?(M=ge(o,ve,ke,2),M?x.appendChild(M):x.textContent=r):x.textContent=r,E=ge(s,ve,ke,2)}else x.textContent=d;let P=null;p&&a&&(P=y("div","persona-send-button-tooltip"),P.textContent=a,v.appendChild(P)),x.setAttribute("aria-label",a),v.appendChild(x);let L="send";return{button:x,wrapper:v,setMode:ve=>{if(ve===L)return;L=ve;let ke=ve==="stop"?i:a;if(x.setAttribute("aria-label",ke),P&&(P.textContent=ke),n){if(M&&E){let se=ve==="stop"?E:M;x.replaceChildren(se)}}else x.textContent=ve==="stop"?l:d}}},Wi=e=>{var P,L,k,I,C,W,_,U,H,F,O,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=((L=t.provider)==null?void 0:L.type)==="runtype";if(!(r||o))return null;let a=(I=(k=e==null?void 0:e.sendButton)==null?void 0:k.size)!=null?I:"40px",i=(C=t.iconName)!=null?C:"mic",d=(W=t.iconSize)!=null?W:a,l=parseFloat(d)||24,p=(U=t.backgroundColor)!=null?U:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,u=(F=t.iconColor)!=null?F:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor,g=y("div","persona-send-button-wrapper"),f=Et("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}}),x=ge(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let M=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((ee=t.showTooltip)!=null?ee:!1)&&M){let Ee=y("div","persona-send-button-tooltip");Ee.textContent=M,g.appendChild(Ee)}return{button:f,wrapper:g}},Hi=e=>{var v,x,M,E,P,L,k,I;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(M=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?M:"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=(L=t.buttonIconName)!=null?L:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(k=t.buttonTooltipText)!=null?k:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ge(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(I=t.buttonTooltipText)!=null?I:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},Bi=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 l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},Di=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ds=e=>{var v,x,M,E,P,L;let{config:t}=e,n=Et("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=Di(),o=Et("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}=Ii(t);a();let i=Ri(t),d=Wi(t),l=Hi(t),p=Bi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),o.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(l==null?void 0:l.button)&&k.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(P=l==null?void 0:l.input)!=null?P:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var kg=()=>{let e=Et("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=ge("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=ge("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Lg=e=>{var v,x,M,E,P,L;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Di();r.style.display="none";let o=Bi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ii(t);s.style.maxHeight="100px",a();let i=Ri(t),d=Wi(t),l=Hi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=Et("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");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(l==null?void 0:l.button)&&k.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(P=l==null?void 0:l.input)!=null?P:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Pg=e=>{var p,u,g,f,v,x,M,E,P,L,k,I,C,W,_,U,H;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=on(e);if(ko(e)){let F=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},O=y("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(v=F.expandedSize)!=null?v:"anchored",O.style.zIndex=String((M=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?M:Sn);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%",O.appendChild(ee);let Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(E=F.expandedSize)!=null?E:"anchored",Ee.style.zIndex=String((L=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?L:Sn),{wrapper:O,panel:ee,pillRoot:Ee}}if(n){let F=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(O),{wrapper:F,panel:O}}if(!t){let F=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ee=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.width)!=null?I:"100%";return F.style.width=ee,O.style.width="100%",F.appendChild(O),{wrapper:F,panel:O}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&vr[o.position]?vr[o.position]:vr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((_=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?_:Sn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(U=e==null?void 0:e.launcher)==null?void 0:U.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:Xn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Xy=(e,t)=>{var k,I,C,W,_,U,H,F,O;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}=Mi(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=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.clearChat)==null?void 0:I.enabled)!=null?C:!0,a=null,i=null;if(s){let ee=ki(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=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=Et("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"}});l.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(_=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?_:"Hello \u{1F44B}"}),u=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),g=Et("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),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let M=Et("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=Lg({config:e}),{root:P,textNode:L}=kg();return n.append(d,o,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:M,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:L}},Ig=(e,t=!0)=>{var M,E,P,L,k,I,C,W,_;if(ko(e))return Xy(e,t);let n=Et("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=(M=e==null?void 0:e.layout)==null?void 0:M.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Bs(e,r,{showClose:t}):eo({config:e,showClose:t}),a=Et("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=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(L=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?L:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),l=Et("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%"),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=Ds({config:e}),v=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;o?ts(n,s,e):(s.header.style.display="none",ts(n,s,e)),n.append(a);let x=Et("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 v||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Vl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
18
|
+
_Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]}),og=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,sg=e=>yo(e)||e===br,Is=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Yo(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(yo(g.name)||g.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&&f&&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==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.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 Jo(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,l;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=(l=(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?l:this.config.agentId;!n||!r||!this.config.clientToken||Rl().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 fa((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=So.isSupported()?new So({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(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,g=t.browserFallback!==!1;if(l&&p&&u)return Rl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:v})=>{let x=new f({host:l,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&n?new v(x,n,{onFallback:M=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${M.message}`)}):x});if(g&&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=Ao(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,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){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:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,l;(l=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||l.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,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(d=this.callbacks).onVoiceStatusChanged)==null||l.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,l,p,u,g,f;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:(l=(d=t.runtype)==null?void 0:d.host)!=null?l: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:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.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(!My(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 Jo(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:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:a!=null?a:n==="user"?ks():n==="assistant"?Xo():`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:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,x={id:d!=null?d:o==="user"?ks():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(x)}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,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...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 l,p,u,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=ks(),s=Xo(),a={id:o,role:"user",content:r||li,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(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let M=rg(v,this.config.errorMessage);if(M){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Xo();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(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=rg(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var 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,g,f,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.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,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let M=null;if(x instanceof Response){if(!x.ok){let E=await x.json().catch(()=>null);throw new Error((g=E==null?void 0:E.error)!=null?g:`Approval request failed: ${x.status}`)}M=x.body}else x instanceof ReadableStream&&(M=x);M?await this.connectStream(M,{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(x){let M=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(v=(f=this.callbacks).onError)==null||v.call(f,x instanceof Error?x:new Error(String(x)))}}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,g,f,v,x,M,E,P,L,k,I;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=(g=t.toolCall)==null?void 0:g.name;if(!o||!s){(v=(f=this.callbacks).onError)==null||v.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(x=t.toolCall)==null?void 0:x.args,W=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(W.length===1){let _=typeof((M=W[0])==null?void 0:M.question)=="string"?W[0].question:"";_&&(a={[_]: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,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([W,_])=>`${W}: ${Array.isArray(_)?_.join(", "):_}`).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:{};l.forEach((W,_)=>{let U=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!U)return;let H=C[U],F=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${_}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${_}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let W=await C.json().catch(()=>null);throw new Error((L=W==null?void 0:W.error)!=null?L:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let W=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(I=(k=this.callbacks).onError)==null||I.call(k,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,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var I,C,W,_,U,H,F;let f=(I=g.toolCall)==null?void 0:I.name,v=(C=g.toolCall)==null?void 0:C.id;if(!f||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let M=this.markWebMcpToolRunning(g),E=(_=(W=g.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?_:f;if(f===br)return{dedupeKey:x,resumeKey:E,output:Sl(),toolMessage:g,startedAt:M,completedAt:Date.now()};let P=new AbortController;this.webMcpResolveControllers.add(P),o.push(P);let L=this.client.executeWebMcpToolCall(f,(U=g.toolCall)==null?void 0:U.args,P.signal),k;if(!L)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await L}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(F=(H=this.callbacks).onError)==null||F.call(H,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(g,ha(Z?"Aborted by cancel()":og(O)),M),this.webMcpInflightKeys.delete(x),null}return P.signal.aborted?(this.markWebMcpToolComplete(g,ha("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:E,output:k,toolMessage:g,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let f=await this.client.resumeFlow(t,g,{signal:s.signal});if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${f.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===br?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ha("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,M,E,P,L,k,I,C,W,_,U;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(M=t.toolCall)==null?void 0:M.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 H=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(H)||this.webMcpResolvedKeys.has(H))return;this.webMcpInflightKeys.add(H);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(H)}catch(F){(k=(L=this.callbacks).onError)==null||k.call(L,F instanceof Error?F:new Error(String(F)))}finally{this.webMcpInflightKeys.delete(H)}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 l=r===br,p=(I=t.toolCall)==null?void 0:I.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let H;if(l?H=Sl():u?H=await u:H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ha("Aborted by cancel()"),a);return}let F=(W=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?W:r;g="resume",await this.resumeWithToolOutput(n,F,H,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,H,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(H){let F=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));(g==="execute"||F||d.aborted)&&this.markWebMcpToolComplete(t,ha(F||d.aborted?"Aborted by cancel()":og(H)),a),F||(U=(_=this.callbacks).onError)==null||U.call(_,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,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.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var 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.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()}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=Il(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ps(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=Il(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,g,f,v,x,M,E,P,L,k,I,C,W,_;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={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let U=o.approval,H=n.approval;a.approval={...U,...H,executionId:H.executionId||U.executionId,toolName:H.toolName||U.toolName,description:H.description||U.description,toolType:(f=H.toolType)!=null?f:U.toolType,reason:(v=H.reason)!=null?v:U.reason,parameters:(x=H.parameters)!=null?x:U.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(E=n.agentMetadata)==null?void 0:E.executionId,l=(P=n.toolCall)==null?void 0:P.id;if(i&&sg(i)&&d&&l&&((L=n.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let U=`${d}:${l}`,H=this.webMcpInflightKeys.has(U),F=this.webMcpResolvedKeys.has(U),O=(k=o.toolCall)==null?void 0:k.name,Z=((I=o.agentMetadata)==null?void 0:I.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&O!==void 0&&sg(O)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(H||F||Z)&&(a.agentMetadata={...(_=a.agentMetadata)!=null?_:{},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,l;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=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var A=require("lucide"),ky={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},ge=(e,t=24,n="currentColor",r=2)=>{let o=ky[e];return o?Ly(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 Ly(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(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var mi={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function Py(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Iy(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 Zo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:mi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:mi.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:mi.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:mi.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 l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Gm(l,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,l,u);continue}try{let u=await Km(l),g=ci(l)?URL.createObjectURL(l):null,f={id:Py(),file:l,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}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=ci(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=Iy(t.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=Jm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),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=ge("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 ag=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ya(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];ag(s)&&ag(o)?n[r]=ya(s,o):n[r]=o}return n}var Gn="min(440px, calc(100vw - 24px))",gi="440px",Ry={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Gn,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:Ry,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ig(e,t){if(!(!e&&!t))return e?t?ya(e,t):e:t}function fi(e){var t,n,r,o,s,a,i,d,l,p,u,g,f,v,x,M,E,P,L,k,I;return e?{...Bt,...e,theme:ig(Bt.theme,e.theme),darkTheme:ig(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 ce,ae,se,xe,Be,K,Q,He,G,ue;let C=(ce=Bt.features)==null?void 0:ce.artifacts,W=(ae=e.features)==null?void 0:ae.artifacts,_=(se=Bt.features)==null?void 0:se.scrollToBottom,U=(xe=e.features)==null?void 0:xe.scrollToBottom,H=(Be=Bt.features)==null?void 0:Be.scrollBehavior,F=(K=e.features)==null?void 0:K.scrollBehavior,O=(Q=Bt.features)==null?void 0:Q.streamAnimation,Z=(He=e.features)==null?void 0:He.streamAnimation,Me=(G=Bt.features)==null?void 0:G.askUserQuestion,pe=(ue=e.features)==null?void 0:ue.askUserQuestion,ee=C===void 0&&W===void 0?void 0:{...C,...W,layout:{...C==null?void 0:C.layout,...W==null?void 0:W.layout}},Ae=_===void 0&&U===void 0?void 0:{..._,...U},Le=H===void 0&&F===void 0?void 0:{...H,...F},oe=O===void 0&&Z===void 0?void 0:{...O,...Z},Ce=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,...Ae!==void 0?{scrollToBottom:Ae}:{},...Le!==void 0?{scrollBehavior:Le}:{},...ee!==void 0?{artifacts:ee}:{},...oe!==void 0?{streamAnimation:oe}:{},...Ce!==void 0?{askUserQuestion:Ce}:{}}})(),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,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(x=(v=Bt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(M=e.layout)==null?void 0:M.messages)==null?void 0:E.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(L=e.layout)==null?void 0:L.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(k=Bt.markdown)==null?void 0:k.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var Wl={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"}},Hl={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"}},Bl={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:Gn,maxWidth:gi,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 Rs(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."))?Rs(e,r):r}function hi(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=Rs(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 Dl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function lg(e,t){let n={...e};for(let[r,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]=lg(s,o):n[r]=o}return n}function Wy(e,t){return t?lg(e,t):e}function Ws(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,M;let n={palette:Wl,semantic:Hl,components:Bl},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,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:Wy(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Dl(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 yi(e){var x,M,E,P,L,k,I,C,W,_,U,H,F,O,Z,Me,pe,ee,Ae,Le,oe,Ce,ce,ae,se,xe,Be,K,Q,He,G,ue,je,fe,Ke,tt,jt,Qe,he,X,pt,ze,Se,ke,rt,It,te,Ue,An,vt,yn,vr,wr,S,ne,Ee,Ne,Ie,Oe,Je,lt,Rt,de,B,ye,_e,wt,Ze,Dt,Et,yt,Pt,Yt,_t,Bn,Ut,Dn,Qn,bn,Ln,Yn,no,Ct,Cr,Ar,Or,dr,mt,Io,Sr,Ro,Pn,is,ro,Fr,oo,so,Wo,Ho,ao,xt,Nn,On,Sn,At,Zn,er,Fn,io,_r,lo,_n,Wt,Tn,tr,co,$r,po;let t=hi(e),n={};for(let[ve,In]of Object.entries(t)){let Tr=ve.replace(/\./g,"-");n[`--persona-${Tr}`]=In.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M: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"]=(L=n["--persona-semantic-colors-background"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(k=n["--persona-semantic-colors-container"])!=null?k:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(I=n["--persona-semantic-colors-text"])!=null?I: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"]=(W=n["--persona-semantic-colors-text-inverse"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(_=n["--persona-semantic-colors-border"])!=null?_: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"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H: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"]=(O=n["--persona-components-voice-processing-icon"])!=null?O:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z: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"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ae=n["--persona-components-approval-requested-shadow"])!=null?Ae:"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"]=(Le=n["--persona-components-approval-approve-background"])!=null?Le:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(oe=n["--persona-components-approval-deny-background"])!=null?oe:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ce=n["--persona-components-attachment-image-background"])!=null?Ce:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ce=n["--persona-components-attachment-image-border"])!=null?ce: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"]=(se=n["--persona-semantic-typography-fontSize"])!=null?se:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(xe=n["--persona-semantic-typography-fontWeight"])!=null?xe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Be=n["--persona-semantic-typography-lineHeight"])!=null?Be: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"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(G=n["--persona-palette-radius-xl"])!=null?G:"0.75rem",n["--persona-radius-full"]=(ue=n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-launcher-radius"]=(fe=(je=n["--persona-components-launcher-borderRadius"])!=null?je:n["--persona-palette-radius-full"])!=null?fe:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(tt=n["--persona-components-launcher-foreground"])!=null?tt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(jt=n["--persona-components-launcher-border"])!=null?jt:n["--persona-border"],n["--persona-button-primary-bg"]=(Qe=n["--persona-components-button-primary-background"])!=null?Qe:n["--persona-primary"],n["--persona-button-primary-fg"]=(he=n["--persona-components-button-primary-foreground"])!=null?he:n["--persona-text-inverse"],n["--persona-button-radius"]=(pt=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?pt:"9999px",n["--persona-panel-radius"]=(Se=(ze=n["--persona-components-panel-borderRadius"])!=null?ze:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(ke=n["--persona-components-panel-border"])!=null?ke:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(It=(rt=n["--persona-components-panel-shadow"])!=null?rt:n["--persona-palette-shadows-xl"])!=null?It:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(te=n["--persona-components-launcher-shadow"])!=null?te:"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"]=(yn=(vt=n["--persona-components-message-user-borderRadius"])!=null?vt:n["--persona-radius-lg"])!=null?yn:"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"]=(S=n["--persona-components-header-background"])!=null?S:n["--persona-surface"],n["--persona-header-border"]=(ne=n["--persona-components-header-border"])!=null?ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ee=n["--persona-components-header-iconBackground"])!=null?Ee:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ne=n["--persona-components-header-iconForeground"])!=null?Ne:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Ie=n["--persona-components-header-titleForeground"])!=null?Ie:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Oe=n["--persona-components-header-subtitleForeground"])!=null?Oe:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Je=n["--persona-components-header-actionIconForeground"])!=null?Je:n["--persona-muted"];let r=(lt=e.components)==null?void 0:lt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Rt=e.components)==null?void 0:Rt.introCard;n["--persona-intro-card-bg"]=(de=n["--persona-components-introCard-background"])!=null?de:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(ye=n["--persona-components-introCard-padding"])!=null?ye:"1.5rem",n["--persona-intro-card-shadow"]=(wt=(_e=o==null?void 0:o.shadow)!=null?_e:n["--persona-components-introCard-shadow"])!=null?wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ze=n["--persona-components-input-background"])!=null?Ze:n["--persona-surface"],n["--persona-input-placeholder"]=(Dt=n["--persona-components-input-placeholder"])!=null?Dt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Et=n["--persona-components-message-user-background"])!=null?Et:n["--persona-accent"],n["--persona-message-user-text"]=(yt=n["--persona-components-message-user-text"])!=null?yt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Pt=n["--persona-components-message-user-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Yt=n["--persona-components-message-assistant-background"])!=null?Yt:n["--persona-surface"],n["--persona-message-assistant-text"]=(_t=n["--persona-components-message-assistant-text"])!=null?_t:n["--persona-text"],n["--persona-message-assistant-border"]=(Bn=n["--persona-components-message-assistant-border"])!=null?Bn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ut=n["--persona-components-message-assistant-shadow"])!=null?Ut:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Qn=(Dn=n["--persona-components-scrollToBottom-background"])!=null?Dn:n["--persona-button-primary-bg"])!=null?Qn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Ln=(bn=n["--persona-components-scrollToBottom-foreground"])!=null?bn:n["--persona-button-primary-fg"])!=null?Ln:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Yn=n["--persona-components-scrollToBottom-border"])!=null?Yn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(no=n["--persona-components-scrollToBottom-size"])!=null?no:"40px",n["--persona-scroll-to-bottom-radius"]=(Ar=(Cr=(Ct=n["--persona-components-scrollToBottom-borderRadius"])!=null?Ct:n["--persona-button-radius"])!=null?Cr:n["--persona-radius-full"])!=null?Ar:"9999px",n["--persona-scroll-to-bottom-shadow"]=(dr=(Or=n["--persona-components-scrollToBottom-shadow"])!=null?Or:n["--persona-palette-shadows-sm"])!=null?dr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(mt=n["--persona-components-scrollToBottom-padding"])!=null?mt:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Io=n["--persona-components-scrollToBottom-gap"])!=null?Io:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Ro=(Sr=n["--persona-components-scrollToBottom-fontSize"])!=null?Sr:n["--persona-palette-typography-fontSize-sm"])!=null?Ro:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Pn=n["--persona-components-scrollToBottom-iconSize"])!=null?Pn:"14px",n["--persona-tool-bubble-shadow"]=(is=n["--persona-components-toolBubble-shadow"])!=null?is:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(ro=n["--persona-components-reasoningBubble-shadow"])!=null?ro:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(oo=n["--persona-components-markdown-inlineCode-background"])!=null?oo:n["--persona-container"],n["--persona-md-inline-code-color"]=(so=n["--persona-components-markdown-inlineCode-foreground"])!=null?so:n["--persona-text"],n["--persona-md-link-color"]=(Ho=(Wo=n["--persona-components-markdown-link-foreground"])!=null?Wo:n["--persona-accent"])!=null?Ho:"#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 l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(ao=n["--persona-components-markdown-codeBlock-background"])!=null?ao:n["--persona-container"],n["--persona-md-code-block-border-color"]=(xt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?xt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Nn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Nn:"inherit",n["--persona-md-table-header-bg"]=(On=n["--persona-components-markdown-table-headerBackground"])!=null?On:n["--persona-container"],n["--persona-md-table-border-color"]=(Sn=n["--persona-components-markdown-table-borderColor"])!=null?Sn:n["--persona-border"],n["--persona-md-hr-color"]=(At=n["--persona-components-markdown-hr-color"])!=null?At:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Zn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Zn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(er=n["--persona-components-markdown-blockquote-background"])!=null?er:"transparent",n["--persona-md-blockquote-text-color"]=(Fn=n["--persona-components-markdown-blockquote-textColor"])!=null?Fn:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(io=n["--persona-components-collapsibleWidget-container"])!=null?io:n["--persona-surface"],n["--cw-surface"]=(_r=n["--persona-components-collapsibleWidget-surface"])!=null?_r:n["--persona-surface"],n["--cw-border"]=(lo=n["--persona-components-collapsibleWidget-border"])!=null?lo:n["--persona-border"],n["--persona-message-border"]=(_n=n["--persona-components-message-border"])!=null?_n: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 g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let ve=v.toolbar;ve.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ve.iconHoverColor),ve.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ve.iconHoverBackground),ve.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ve.iconPadding),ve.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ve.iconBorderRadius),ve.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ve.iconBorder),ve.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ve.toggleGroupGap),ve.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ve.toggleBorderRadius),ve.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ve.copyBackground),ve.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ve.copyBorder),ve.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ve.copyColor),ve.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ve.copyBorderRadius),ve.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ve.copyPadding),ve.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ve.copyMenuBackground,n["--persona-dropdown-bg"]=(Wt=n["--persona-dropdown-bg"])!=null?Wt:ve.copyMenuBackground),ve.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ve.copyMenuBorder,n["--persona-dropdown-border"]=(Tn=n["--persona-dropdown-border"])!=null?Tn:ve.copyMenuBorder),ve.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ve.copyMenuShadow,n["--persona-dropdown-shadow"]=(tr=n["--persona-dropdown-shadow"])!=null?tr:ve.copyMenuShadow),ve.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ve.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(co=n["--persona-dropdown-radius"])!=null?co:ve.copyMenuBorderRadius),ve.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ve.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=($r=n["--persona-dropdown-item-hover-bg"])!=null?$r:ve.copyMenuItemHoverBackground),ve.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ve.iconBackground),ve.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ve.toolbarBorder)}if(v!=null&&v.tab){let ve=v.tab;ve.background&&(n["--persona-artifact-tab-bg"]=ve.background),ve.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ve.activeBackground),ve.activeBorder&&(n["--persona-artifact-tab-active-border"]=ve.activeBorder),ve.borderRadius&&(n["--persona-artifact-tab-radius"]=ve.borderRadius),ve.textColor&&(n["--persona-artifact-tab-color"]=ve.textColor),ve.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ve.hoverBackground),ve.listBackground&&(n["--persona-artifact-tab-list-bg"]=ve.listBackground),ve.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ve.listBorderColor),ve.listPadding&&(n["--persona-artifact-tab-list-padding"]=ve.listPadding)}if(v!=null&&v.pane){let ve=v.pane;if(ve.toolbarBackground){let In=(po=Rs(e,ve.toolbarBackground))!=null?po:ve.toolbarBackground;n["--persona-artifact-toolbar-bg"]=In}}return n}var cg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Hy={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},ba=()=>{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"},By=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ba()},Nl=e=>By(e),Dy=e=>Ws(e),Ny=e=>{var n;let t=Ws(void 0,{validate:!1});return Ws({...e,palette:{...t.palette,colors:{...Hy.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Hs=e=>{let t=Nl(e),n=dg(e==null?void 0:e.theme),r=dg(e==null?void 0:e.darkTheme);return t==="dark"?Ny(ya(n!=null?n:{},r!=null?r:{})):Dy(n)},Oy=e=>yi(e),To=(e,t)=>{let n=Hs(t),r=Oy(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},bi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ba())});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(ba());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var pg=require("idiomorph"),xi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;pg.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:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var ug=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var vi={index:-1,draft:""};function mg(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:{...vi}}}function gg(e,t){var n,r,o,s,a,i,d,l,p,u,g,f,v,x,M,E,P,L,k,I,C,W,_,U,H,F,O,Z,Me,pe,ee,Ae,Le,oe,Ce,ce,ae,se;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=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(M=(x=e.toolCall)==null?void 0:x.name)!=null?M:"",(L=(P=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:P.length)!=null?L:0,(W=(C=(I=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?W:"",typeof((_=e.toolCall)==null?void 0:_.args)=="string"?e.toolCall.args.length:(U=e.toolCall)!=null&&U.args?JSON.stringify(e.toolCall.args).length:0,(O=(F=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:F.length)!=null?O:0,(ee=(pe=(Me=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(Ce=(oe=(Le=(Ae=e.reasoning)==null?void 0:Ae.chunks)==null?void 0:Le[e.reasoning.chunks.length-1])==null?void 0:oe.slice(-32))!=null?Ce:"",(ae=(ce=e.contentParts)==null?void 0:ce.length)!=null?ae:0,(se=e.stopReason)!=null?se:"",t].join("\0")}function fg(){return new Map}function hg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function yg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function bg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function wi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Yr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function es(e,t){return Yr(e)-e.scrollTop<=t}function Ci(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||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 Ai(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 xg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function vg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function wg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var wn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,Eo=Cn+1;var xa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Fy=["pre","code","a","script","style"],Si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:xa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:xa.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:xa.speed,duration:(o=e==null?void 0:e.duration)!=null?o:xa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:xa.buffer}},Ag=[{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"}],va=new Map;for(let e of Ag)va.set(e.name,e);var Sg=e=>{va.set(e.name,e)},Tg=e=>{Ag.some(t=>t.name===e)||va.delete(e)},Eg=()=>Array.from(va.keys()),wa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=va.get(e))!=null?r:null},Ti=(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},_y=(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},$y=(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},Ol=/\s/,jy=(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},Uy=(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(Ol.test(s[i])){let l=i;for(;l<s.length&&Ol.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Ol.test(s[p]);)l.appendChild(_y(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},qy=(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 l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild($y(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},Ca=(e,t,n,r)=>{var u,g;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:Fy).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)jy(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Uy:qy;for(let f of i)p(f,n,l);return o.innerHTML},Ei=(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},Aa=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Cg=new WeakMap,zy=(e,t)=>{var s;if(!e.styles)return;let n=Cg.get(t);if(n||(n=new Set,Cg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let 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)},Fl=new WeakMap,Vy=(e,t)=>{if(!e.onAttach)return;let n=Fl.get(t);if(n||(n=new Map,Fl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Mg=e=>{let t=Fl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},_l=(e,t)=>{zy(e,t),Vy(e,t)};function $l(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 Sa=0,Mo=null;function jl(e=document){var n;if(Sa++,Sa===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Mo={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,Sa=Math.max(0,Sa-1),Sa===0&&Mo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Mo.originalOverflow,o.style.position=Mo.originalPosition,o.style.top=Mo.originalTop,o.style.width=Mo.originalWidth,s.scrollTo(0,Mo.scrollY),Mo=null}}}var Ta={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"},ko=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Jn=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:Ta.side,width:(o=t==null?void 0:t.width)!=null?o:Ta.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ta.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ta.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Ta.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 Ky="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Mi=(e,t={})=>{var M,E,P,L,k,I;let{showClose:n=!0,wrapperClassName:r=Ky,buttonSize:o,iconSize:s="28px"}=t,a=(M=e==null?void 0:e.launcher)!=null?M:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=y("div",r),l=(P=a.closeButtonTooltipText)!=null?P:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0,u=(k=a.closeButtonIconName)!=null?k:"x",g=(I=a.closeButtonIconText)!=null?I:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Tt("button",{className:oa("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||kn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=ge(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,W=()=>{if(C)return;let U=v.ownerDocument,H=U.body;if(!H)return;C=Dr(U,"div","persona-clear-chat-tooltip"),C.textContent=l;let F=Dr(U,"div");F.className="persona-clear-chat-tooltip-arrow",C.appendChild(F);let O=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Eo),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",H.appendChild(C)},_=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",_),v.addEventListener("focus",W),v.addEventListener("blur",_),d._cleanupTooltip=()=>{_(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",_),v.removeEventListener("focus",W),v.removeEventListener("blur",_)}}return{button:v,wrapper:d}},Gy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ki=(e,t={})=>{var C,W,_,U,H,F,O,Z,Me,pe,ee,Ae,Le;let{wrapperClassName:n=Gy,buttonSize:r,iconSize:o="20px"}=t,a=(W=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?W:{},i=(_=r!=null?r:a.size)!=null?_:"32px",d=(U=a.iconName)!=null?U:"refresh-cw",l=(H=a.iconColor)!=null?H:"",p=(F=a.backgroundColor)!=null?F:"",u=(O=a.borderWidth)!=null?O:"",g=(Z=a.borderColor)!=null?Z:"",f=(Me=a.borderRadius)!=null?Me:"",v=(pe=a.paddingX)!=null?pe:"",x=(ee=a.paddingY)!=null?ee:"",M=(Ae=a.tooltipText)!=null?Ae:"Clear chat",E=(Le=a.showTooltip)!=null?Le:!0,P=y("div",n),L=!!(u||g),k=Tt("button",{className:oa("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!L&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:l||kn.actionIconColor,backgroundColor:p||void 0,border:L?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),I=ge(d,o,"currentColor",1);if(I&&(I.style.display="block",k.appendChild(I)),P.appendChild(k),E&&M){let oe=null,Ce=()=>{if(oe)return;let ae=k.ownerDocument,se=ae.body;if(!se)return;oe=Dr(ae,"div","persona-clear-chat-tooltip"),oe.textContent=M;let xe=Dr(ae,"div");xe.className="persona-clear-chat-tooltip-arrow",oe.appendChild(xe);let Be=k.getBoundingClientRect();oe.style.position="fixed",oe.style.zIndex=String(Eo),oe.style.left=`${Be.left+Be.width/2}px`,oe.style.top=`${Be.top-8}px`,oe.style.transform="translate(-50%, -100%)",se.appendChild(oe)},ce=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};P.addEventListener("mouseenter",Ce),P.addEventListener("mouseleave",ce),k.addEventListener("focus",Ce),k.addEventListener("blur",ce),P._cleanupTooltip=()=>{ce(),P.removeEventListener("mouseenter",Ce),P.removeEventListener("mouseleave",ce),k.removeEventListener("focus",Ce),k.removeEventListener("blur",ce)}}return{button:k,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 I,C,W,_,U,H,F,O,Z,Me,pe,ee,Ae,Le,oe,Ce;let{config:t,showClose:n=!0}=e,r=Tt("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=(C=o.headerIconSize)!=null?C:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",i=(_=o.headerIconHidden)!=null?_:!1,d=o.headerIconName,l=Tt("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 ce=parseFloat(s)||24,ae=ge(d,ce*.6,"currentColor",1);ae?l.replaceChildren(ae):l.textContent=(H=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?H:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let ce=y("img");ce.src=t.launcher.iconUrl,ce.alt="",ce.className="persona-rounded-xl persona-object-cover",ce.style.height=s,ce.style.width=s,l.replaceChildren(ce)}else l.textContent=(Z=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Tt("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}}),g=Tt("span",{className:"persona-text-xs",text:(Ae=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Ae:"Here to help you get answers fast",style:{color:kn.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(Le=o.clearChat)!=null?Le:{},v=(oe=f.enabled)!=null?oe:!0,x=(Ce=f.placement)!=null?Ce:"inline",M=null,E=null;if(v){let ae=ki(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=ae.button,E=ae.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:L,wrapper:k}=Mi(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:L,closeButtonWrapper:k,clearChatButton:M,clearChatButtonWrapper:E}},ts=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"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 Lo(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(Eo)):(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 f of t){if(f.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let M=ge(f.icon,16,"currentColor",1.5);M&&v.appendChild(M)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",M=>{M.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}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 l=ge(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Ea(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=ge(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function Ma(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 l(p){a=p,d()}return{element:s,setSelected:l}}function Li(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=ge(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,M;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Lo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Ul=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 Jy(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=ge(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 l=Lo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ql=e=>{var P,L,k,I,C,W,_,U,H;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,l,p;if(d)l=Li({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=kn.titleColor,p=(k=l.querySelector(".persona-combo-btn-label"))!=null?k:l;else{if(l=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=(I=a.title)!=null?I:"Chat Assistant",l.appendChild(p),Jy(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=o.onTitleClick;l.addEventListener("click",Z=>{Z.target.closest("button")||O()}),l.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),O())})}let F=o==null?void 0:o.titleRowHover;F&&(l.style.borderRadius=(W=F.borderRadius)!=null?W:"10px",l.style.padding=(_=F.padding)!=null?_:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var O,Z;l.style.backgroundColor=(O=F.background)!=null?O:"",l.style.borderColor=(Z=F.border)!=null?Z:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(U=a.closeButtonSize)!=null?U:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||kn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=ge(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let M=y("div");M.style.display="none";let E=y("span");return E.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:E,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Pi={default:Ul,minimal:ql},zl=e=>{var t;return(t=Pi[e])!=null?t:Pi.default},Bs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=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"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,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 Ii=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}},Ri=e=>{var I,C,W,_,U,H,F,O,Z,Me,pe,ee;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(C=t.useIcon)!=null?C:!1,r=(W=t.iconText)!=null?W:"\u2191",o=t.iconName,s=(_=t.stopIconName)!=null?_:"square",a=(U=t.tooltipText)!=null?U:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(O=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?O:"Send",l=(Me=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Me:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(ee=t.size)!=null?ee:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=Tt("button",{className:oa("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,E=null;if(n){let Ae=parseFloat(u)||24,Le=(f==null?void 0:f.trim())||"currentColor";o?(M=ge(o,Ae,Le,2),M?x.appendChild(M):x.textContent=r):x.textContent=r,E=ge(s,Ae,Le,2)}else x.textContent=d;let P=null;p&&a&&(P=y("div","persona-send-button-tooltip"),P.textContent=a,v.appendChild(P)),x.setAttribute("aria-label",a),v.appendChild(x);let L="send";return{button:x,wrapper:v,setMode:Ae=>{if(Ae===L)return;L=Ae;let Le=Ae==="stop"?i:a;if(x.setAttribute("aria-label",Le),P&&(P.textContent=Le),n){if(M&&E){let oe=Ae==="stop"?E:M;x.replaceChildren(oe)}}else x.textContent=Ae==="stop"?l:d}}},Wi=e=>{var P,L,k,I,C,W,_,U,H,F,O,Z;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=((L=t.provider)==null?void 0:L.type)==="runtype";if(!(r||o))return null;let a=(I=(k=e==null?void 0:e.sendButton)==null?void 0:k.size)!=null?I:"40px",i=(C=t.iconName)!=null?C:"mic",d=(W=t.iconSize)!=null?W:a,l=parseFloat(d)||24,p=(U=t.backgroundColor)!=null?U:(_=e==null?void 0:e.sendButton)==null?void 0:_.backgroundColor,u=(F=t.iconColor)!=null?F:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor,g=y("div","persona-send-button-wrapper"),f=Tt("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}}),x=ge(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let M=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&M){let Me=y("div","persona-send-button-tooltip");Me.textContent=M,g.appendChild(Me)}return{button:f,wrapper:g}},Hi=e=>{var v,x,M,E,P,L,k,I;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(M=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?M:"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:Qr).join(","),o.multiple=((P=t.maxFiles)!=null?P:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(L=t.buttonIconName)!=null?L:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(k=t.buttonTooltipText)!=null?k:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ge(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(I=t.buttonTooltipText)!=null?I:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},Bi=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 l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},Di=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ds=e=>{var v,x,M,E,P,L;let{config:t}=e,n=Tt("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=Di(),o=Tt("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}=Ii(t);a();let i=Ri(t),d=Wi(t),l=Hi(t),p=Bi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),o.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(l==null?void 0:l.button)&&k.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(P=l==null?void 0:l.input)!=null?P:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var kg=()=>{let e=Tt("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=ge("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=ge("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Lg=e=>{var v,x,M,E,P,L;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Di();r.style.display="none";let o=Bi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ii(t);s.style.maxHeight="100px",a();let i=Ri(t),d=Wi(t),l=Hi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("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");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(l==null?void 0:l.button)&&k.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(P=l==null?void 0:l.input)!=null?P:null,attachmentPreviewsContainer:(L=l==null?void 0:l.previewsContainer)!=null?L:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Pg=e=>{var p,u,g,f,v,x,M,E,P,L,k,I,C,W,_,U,H;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=on(e);if(ko(e)){let F=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},O=y("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(v=F.expandedSize)!=null?v:"anchored",O.style.zIndex=String((M=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?M:Cn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",O.appendChild(Z);let Me=y("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((L=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?L:Cn),{wrapper:O,panel:Z,pillRoot:Me}}if(n){let F=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(O),{wrapper:F,panel:O}}if(!t){let F=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.width)!=null?I:"100%";return F.style.width=Z,O.style.width="100%",F.appendChild(O),{wrapper:F,panel:O}}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((_=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?_:Cn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(U=e==null?void 0:e.launcher)==null?void 0:U.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:Gn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Xy=(e,t)=>{var k,I,C,W,_,U,H,F,O;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}=Mi(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=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.clearChat)==null?void 0:I.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=ki(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=Tt("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"}});l.style.setProperty("scrollbar-gutter","stable");let p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(_=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?_:"Hello \u{1F44B}"}),u=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),g=Tt("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),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let M=Tt("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=Lg({config:e}),{root:P,textNode:L}=kg();return n.append(d,o,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:M,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:L}},Ig=(e,t=!0)=>{var M,E,P,L,k,I,C,W,_;if(ko(e))return Xy(e,t);let n=Tt("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=(M=e==null?void 0:e.layout)==null?void 0:M.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Bs(e,r,{showClose:t}):Zr({config:e,showClose:t}),a=Tt("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=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(L=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?L:"Hello \u{1F44B}"}),d=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),l=Tt("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%"),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=Ds({config:e}),v=((_=e==null?void 0:e.layout)==null?void 0:_.showFooter)!==!1;o?ts(n,s,e):(s.header.style.display="none",ts(n,s,e)),n.append(a);let x=Tt("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 v||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Vl=(e,t)=>{let n=y("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 ha=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 L,k,I,C,W,_,U,H,F,O,ee,Ee,ue;let a=(L=s.launcher)!=null?L:{},i=on(s),d=n.querySelector("[data-role='launcher-title']");if(d){let te=(k=a.title)!=null?k:"Chat Assistant";d.textContent=te,d.setAttribute("title",te)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let te=(I=a.subtitle)!=null?I:"Here to help you get answers fast";l.textContent=te,l.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 ve=parseFloat(te)||24,ke=ge(a.agentIconName,ve*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),u.style.display=""):(u.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let te=(U=a.agentIconSize)!=null?U:"40px";g.style.height=te,g.style.width=te,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let te=(H=a.callToActionIconSize)!=null?H:"32px";f.style.height=te,f.style.width=te,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let ve=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,ve=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let ke=parseFloat(te)||24,se=Math.max(ke-ve,8),xe=ge(a.callToActionIconName,se,"currentColor",2);xe?f.appendChild(xe):f.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}let v=a.position&&vr[a.position]?vr[a.position]:vr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${x} ${v}`,i||(n.style.zIndex=String((ee=a.zIndex)!=null?ee:Sn));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=(Ee=a.border)!=null?Ee: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=(ue=a.collapsedMaxWidth)!=null?ue:"",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 Rg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Pg(e),s=Ig(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},l={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:l,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{l.footer.replaceWith(g),l.footer=g}}},Kl=({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:()=>Vl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=Vl(e,n);return{instance:o,element:o.element}};var Qy=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}},Yy=(e,t)=>{if(!e)return null;let n=Qy(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Zy=(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},eb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Gl=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(":"))},Jl=320,Hg=320,tb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ob=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),sb=(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 l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Jl}px`,l.style.maxHeight=`${Hg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),eb(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},ab=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(!Gl(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=`${Jl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ib=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(!Gl(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=`${Jl}px`,o.style.maxHeight=`${Hg}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}},lb=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(!Gl(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}},ns=()=>{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},Xl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ns};if(t){let o=t(r);if(o!==null)return o}return ns()},cb=(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},Wg=(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},db=(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},Ql=(e,t,n)=>{var v,x,M,E,P,L,k;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(M=t.showDownvote)!=null?M:!0,a=(E=t.showReadAloud)!=null?E:!1;if(!r&&!o&&!s&&!a){let I=y("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=(L=t.align)!=null?L:"right",l=(k=t.layout)!=null?k:"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"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(I,C,W)=>{let _=Gt({icon:I,label:C,size:14,className:"persona-message-action-btn"});return _.setAttribute("data-action",W),_};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Ns=(e,t,n,r,o,s)=>{var pe,ie,ae,He,Fe,K,G,we,X,de,We,fe,Ge,nt,Pt,Ze,$e;let a=n!=null?n:{},i=(pe=a.layout)!=null?pe:"bubble",d=a.avatar,l=a.timestamp,p=(ie=d==null?void 0:d.show)!=null?ie:!1,u=(ae=l==null?void 0:l.show)!=null?ae:!1,g=(He=d==null?void 0:d.position)!=null?He:"left",f=(Fe=l==null?void 0:l.position)!=null?Fe:"below",v=db(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=tb(e),E=(G=(K=e.content)==null?void 0:K.trim())!=null?G:"",L=M.length>0&&E===li,k=Si((X=(we=s==null?void 0:s.widgetConfig)==null?void 0:we.features)==null?void 0:X.streamAnimation),I=(fe=(We=(de=s==null?void 0:s.widgetConfig)==null?void 0:de.features)==null?void 0:We.streamAnimation)==null?void 0:fe.plugins,C=e.role==="assistant"&&k.type!=="none"?wa(k.type,I):null,W=e.role==="assistant"&&((Ge=C==null?void 0:C.isAnimating)==null?void 0:Ge.call(C,e))===!0,_=e.role==="assistant"&&C!==null&&(!!e.streaming||W);_&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),_&&C&&(C.containerClass&&U.classList.add(C.containerClass),U.style.setProperty("--persona-stream-step",`${k.speed}ms`),U.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let H=_?Ti((nt=e.content)!=null?nt:"",k.buffer,C,e,!!e.streaming):(Pt=e.content)!=null?Pt:"",F=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=F;_&&(C==null?void 0:C.wrap)==="char"?O=Ca(F,"char",e.id,{skipTags:C.skipTags}):_&&(C==null?void 0:C.wrap)==="word"&&(O=Ca(F,"word",e.id,{skipTags:C.skipTags}));let ee=null;if(L?(ee=document.createElement("div"),ee.innerHTML=O,ee.style.display="none",U.appendChild(ee)):U.innerHTML=O,_&&(C!=null&&C.useCaret)&&!L&&E){let J=Ei(),Ve=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=Ve[Ve.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(J,ze.nextSibling);else{let Ce=U.lastElementChild;Ce?Ce.appendChild(J):U.appendChild(J)}}if(u&&f==="inline"&&e.createdAt){let J=Wg(e,l,"span");J.classList.add("persona-timestamp-inline");let Ve=U.lastElementChild;Ve?Ve.appendChild(J):U.appendChild(J)}if(M.length>0){let J=sb(M,!L&&!!E,()=>{L&&ee&&(ee.style.display="")});J?x.appendChild(J):L&&ee&&(ee.style.display="")}let Ee=nb(e);if(Ee.length>0){let J=ab(Ee);J&&x.appendChild(J)}let ue=rb(e);if(ue.length>0){let J=ib(ue);J&&x.appendChild(J)}let te=ob(e);if(te.length>0){let J=lb(te);J&&x.appendChild(J)}if(x.appendChild(U),u&&f==="below"&&e.createdAt){let J=Wg(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let ve=e.role==="assistant"?Yy(e.stopReason,($e=(Ze=s==null?void 0:s.widgetConfig)==null?void 0:Ze.copy)==null?void 0:$e.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(H&&H.trim()),Ve=k.placeholder==="skeleton",ze=Ve&&k.buffer==="line"&&J;if(J)ze&&x.appendChild(Aa());else if(Ve)x.appendChild(Aa());else{let Ce=Xl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ce&&x.appendChild(Ce)}}if(ve&&e.stopReason&&!e.streaming&&(E||(U.style.display="none"),x.appendChild(Zy(e.stopReason,ve))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Ql(e,r,o);x.appendChild(J)}if(!p||e.role==="system")return x;let se=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),xe=cb(d,e.role);return g==="right"||g==="left"&&e.role==="user"?se.append(x,xe):se.append(xe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),se},Bg=(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}):Ns(e,t,n,r,o,s)};var Os=new Set,pb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ub=(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
|
-
`):""},Dg=(e,t)=>{let n=Os.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 l=ge(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Yl=(e,t)=>{var
|
|
27
|
+
`,n.addEventListener("click",t);let r=s=>{var L,k,I,C,W,_,U,H,F,O,Z,Me,pe;let a=(L=s.launcher)!=null?L:{},i=on(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(k=a.title)!=null?k:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ee=(I=a.subtitle)!=null?I:"Here to help you get answers fast";l.textContent=ee,l.setAttribute("title",ee)}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 ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,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 Ae=parseFloat(ee)||24,Le=ge(a.agentIconName,Ae*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(u.appendChild(Le),u.style.display=""):(u.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(_=a.agentIconText)!=null?_:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(U=a.agentIconSize)!=null?U:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ee=(H=a.callToActionIconSize)!=null?H:"32px";f.style.height=ee,f.style.width=ee,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ae=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ae=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Le=parseFloat(ee)||24,oe=Math.max(Le-Ae,8),Ce=ge(a.callToActionIconName,oe,"currentColor",2);Ce?f.appendChild(Ce):f.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${x} ${v}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z: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 Rg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Pg(e),s=Ig(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},l={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:l,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{l.footer.replaceWith(g),l.footer=g}}},Kl=({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:()=>Vl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=Vl(e,n);return{instance:o,element:o.element}};var Qy=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}},Yy=(e,t)=>{if(!e)return null;let n=Qy(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Zy=(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},eb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Gl=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(":"))},Jl=320,Hg=320,tb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ob=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),sb=(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 l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Jl}px`,l.style.maxHeight=`${Hg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),eb(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},ab=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(!Gl(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=`${Jl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ib=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(!Gl(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=`${Jl}px`,o.style.maxHeight=`${Hg}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}},lb=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(!Gl(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}},ns=()=>{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},Xl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ns};if(t){let o=t(r);if(o!==null)return o}return ns()},cb=(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},Wg=(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},db=(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},Ql=(e,t,n)=>{var v,x,M,E,P,L,k;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(M=t.showDownvote)!=null?M:!0,a=(E=t.showReadAloud)!=null?E:!1;if(!r&&!o&&!s&&!a){let I=y("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=(L=t.align)!=null?L:"right",l=(k=t.layout)!=null?k:"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"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(I,C,W)=>{let _=Gt({icon:I,label:C,size:14,className:"persona-message-action-btn"});return _.setAttribute("data-action",W),_};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Ns=(e,t,n,r,o,s)=>{var ce,ae,se,xe,Be,K,Q,He,G,ue,je,fe,Ke,tt,jt,Qe,he;let a=n!=null?n:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,l=a.timestamp,p=(ae=d==null?void 0:d.show)!=null?ae:!1,u=(se=l==null?void 0:l.show)!=null?se:!1,g=(xe=d==null?void 0:d.position)!=null?xe:"left",f=(Be=l==null?void 0:l.position)!=null?Be:"below",v=db(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=tb(e),E=(Q=(K=e.content)==null?void 0:K.trim())!=null?Q:"",L=M.length>0&&E===li,k=Si((G=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.features)==null?void 0:G.streamAnimation),I=(fe=(je=(ue=s==null?void 0:s.widgetConfig)==null?void 0:ue.features)==null?void 0:je.streamAnimation)==null?void 0:fe.plugins,C=e.role==="assistant"&&k.type!=="none"?wa(k.type,I):null,W=e.role==="assistant"&&((Ke=C==null?void 0:C.isAnimating)==null?void 0:Ke.call(C,e))===!0,_=e.role==="assistant"&&C!==null&&(!!e.streaming||W);_&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),_&&C&&(C.containerClass&&U.classList.add(C.containerClass),U.style.setProperty("--persona-stream-step",`${k.speed}ms`),U.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let H=_?Ti((tt=e.content)!=null?tt:"",k.buffer,C,e,!!e.streaming):(jt=e.content)!=null?jt:"",F=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=F;_&&(C==null?void 0:C.wrap)==="char"?O=Ca(F,"char",e.id,{skipTags:C.skipTags}):_&&(C==null?void 0:C.wrap)==="word"&&(O=Ca(F,"word",e.id,{skipTags:C.skipTags}));let Z=null;if(L?(Z=document.createElement("div"),Z.innerHTML=O,Z.style.display="none",U.appendChild(Z)):U.innerHTML=O,_&&(C!=null&&C.useCaret)&&!L&&E){let X=Ei(),pt=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=pt[pt.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(X,ze.nextSibling);else{let Se=U.lastElementChild;Se?Se.appendChild(X):U.appendChild(X)}}if(u&&f==="inline"&&e.createdAt){let X=Wg(e,l,"span");X.classList.add("persona-timestamp-inline");let pt=U.lastElementChild;pt?pt.appendChild(X):U.appendChild(X)}if(M.length>0){let X=sb(M,!L&&!!E,()=>{L&&Z&&(Z.style.display="")});X?x.appendChild(X):L&&Z&&(Z.style.display="")}let Me=nb(e);if(Me.length>0){let X=ab(Me);X&&x.appendChild(X)}let pe=rb(e);if(pe.length>0){let X=ib(pe);X&&x.appendChild(X)}let ee=ob(e);if(ee.length>0){let X=lb(ee);X&&x.appendChild(X)}if(x.appendChild(U),u&&f==="below"&&e.createdAt){let X=Wg(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let Ae=e.role==="assistant"?Yy(e.stopReason,(he=(Qe=s==null?void 0:s.widgetConfig)==null?void 0:Qe.copy)==null?void 0:he.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(H&&H.trim()),pt=k.placeholder==="skeleton",ze=pt&&k.buffer==="line"&&X;if(X)ze&&x.appendChild(Aa());else if(pt)x.appendChild(Aa());else{let Se=Xl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&x.appendChild(Se)}}if(Ae&&e.stopReason&&!e.streaming&&(E||(U.style.display="none"),x.appendChild(Zy(e.stopReason,Ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=Ql(e,r,o);x.appendChild(X)}if(!p||e.role==="system")return x;let oe=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ce=cb(d,e.role);return g==="right"||g==="left"&&e.role==="user"?oe.append(x,Ce):oe.append(Ce,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),oe},Bg=(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}):Ns(e,t,n,r,o,s)};var Os=new Set,pb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ub=(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
|
+
`):""},Dg=(e,t)=>{let n=Os.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 l=ge(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Yl=(e,t)=>{var pe,ee,Ae,Le,oe,Ce,ce,ae,se,xe,Be;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=(ee=(pe=t==null?void 0:t.features)==null?void 0:pe.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&Os.has(e.id),i=n.status!=="complete",d=ub(e,(Ae=o.previewMaxLines)!=null?Ae:3),l=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");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.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"),g="Thinking...",f=(Le=t==null?void 0:t.reasoning)!=null?Le:{},v=String((oe=n.startedAt)!=null?oe:Date.now()),x=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=ti(n),K},M=(Ce=f.renderCollapsedSummary)==null?void 0:Ce.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ti(n),createElapsedElement:x});typeof M=="string"&&M.trim()?(u.textContent=M,p.appendChild(u)):M instanceof HTMLElement?p.appendChild(M):(u.textContent=g,p.appendChild(u));let E=y("span","persona-text-xs persona-text-persona-primary");E.textContent=Wm(n),p.appendChild(E);let P=(ce=o.loadingAnimation)!=null?ce:"none",L=f.activeTextTemplate,k=f.completeTextTemplate,I=i?L:k,C=M instanceof HTMLElement,W=(K,Q,He)=>{let G=He;for(let ue of Q){let je=y("span","persona-tool-char");je.style.setProperty("--char-index",String(G)),je.textContent=ue===" "?"\xA0":ue,K.appendChild(je),G++}return G},_=(K,Q)=>{u.textContent="";let He=ni(K,""),G=0;for(let ue of He){let je=ue.styles.length>0?(()=>{let fe=y("span",ue.styles.map(Ke=>`persona-tool-text-${Ke}`).join(" "));return u.appendChild(fe),fe})():u;if(ue.isDuration&&i)je.appendChild(x());else{let fe=ue.isDuration?ti(n):ue.text;Q?G=W(je,fe,G):je.appendChild(document.createTextNode(fe))}}};if(!C&&I)if(E.style.display="none",u.style.display="",i&&P!=="none"){let K=(ae=f.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`),_(I,!1)):(u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),P==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),_(I,!0))}else _(I,!1);else if(!C&&i&&P!=="none"){u.style.display="";let K=(se=f.loadingAnimationDuration)!=null?se: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"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Q=u.textContent||g;u.textContent="",W(u,Q,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(s){U=y("div","persona-flex persona-items-center");let Q=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?U.appendChild(Q):U.textContent=a?"Hide":"Show";let He=y("div","persona-flex persona-items-center persona-ml-auto");He.append(U),l.append(p,He)}else l.append(p);let H=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(Be=(xe=t==null?void 0:t.reasoning)==null?void 0:xe.renderCollapsedPreview)==null?void 0:Be.call(xe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});pb(H,K)||(H.textContent=d),H.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,H),r;let F=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let O=n.chunks.join(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(Z),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Q=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?U.appendChild(Q):U.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,F),r};var Fs=new Set,mb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),gb=(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
29
|
`);let o=Co(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
30
|
-
`):""},Zl=(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)"},fb=(e,t)=>{var p,u,g,f,v;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=gb(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Hm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=kl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=kl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Ng=(e,t,n)=>{var p;let r=Fs.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"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=ge(r?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},ec=(e,t)=>{var O,ee,Ee,ue,te,ve,ke,se,xe;let n=e.toolCall,r=(O=t==null?void 0:t.toolCall)!=null?O:{},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=(Ee=(ee=t==null?void 0:t.features)==null?void 0:ee.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Fs.has(e.id),{summary:d,previewText:l,isActive:p}=fb(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 g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let v=String((ue=n.startedAt)!=null?ue:Date.now()),x=()=>{let pe=y("span","");return pe.setAttribute("data-tool-elapsed",v),pe.textContent=pa(n),pe},M=(ve=r.renderCollapsedSummary)==null?void 0:ve.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(te=s.collapsedMode)!=null?te:"tool-call",isActive:p,config:t!=null?t:{},elapsed:pa(n),createElapsedElement:x});typeof M=="string"&&M.trim()?(f.textContent=M,g.appendChild(f)):M instanceof HTMLElement?g.appendChild(M):(f.textContent=d,g.appendChild(f));let E=(ke=s.loadingAnimation)!=null?ke:"none",P=r.activeTextTemplate,L=r.completeTextTemplate,k=p?P:L,I=M instanceof HTMLElement,C=(pe,ie,ae)=>{let He=ae;for(let Fe of ie){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(He)),K.textContent=Fe===" "?"\xA0":Fe,pe.appendChild(K),He++}return He},W=(pe,ie)=>{var K;f.textContent="";let ae=((K=n.name)==null?void 0:K.trim())||"tool",He=ni(pe,ae),Fe=0;for(let G of He){let we=G.styles.length>0?(()=>{let X=y("span",G.styles.map(de=>`persona-tool-text-${de}`).join(" "));return f.appendChild(X),X})():f;if(G.isDuration&&p)we.appendChild(x());else{let X=G.isDuration?pa(n):G.text;ie?Fe=C(we,X,Fe):we.appendChild(document.createTextNode(X))}}};if(!I)if(p&&E!=="none"){let pe=(se=r.loadingAnimationDuration)!=null?se:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),k&&W(k,!1);else if(f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)W(k,!0);else{let ie=f.textContent||d;f.textContent="",C(f,ie,0)}}else k&&W(k,!1);let _=null;if(a){_=y("div","persona-flex persona-items-center");let pe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ie=ge(i?"chevron-up":"chevron-down",16,pe,2);ie?_.appendChild(ie):_.textContent=i?"Hide":"Show";let ae=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(_),u.append(g,ae)}else u.append(g);let U=y("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&&l){let pe=(xe=r.renderCollapsedPreview)==null?void 0:xe.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});mb(U,pe)||(U.textContent=l),U.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,U),o;let H=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let pe=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?pe.style.color=r.contentTextColor:r.headerTextColor&&(pe.style.color=r.headerTextColor),pe.textContent=n.name,H.appendChild(pe)}if(n.args!==void 0){let pe=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Arguments";let ae=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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Zl(ae,r),ae.textContent=Co(n.args),pe.append(ie,ae),H.appendChild(pe)}if(n.chunks&&n.chunks.length){let pe=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Activity";let ae=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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Zl(ae,r),ae.textContent=n.chunks.join(""),pe.append(ie,ae),H.appendChild(pe)}if(n.status==="complete"&&n.result!==void 0){let pe=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Result";let ae=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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Zl(ae,r),ae.textContent=Co(n.result),pe.append(ie,ae),H.appendChild(pe)}if(n.status==="complete"&&typeof n.duration=="number"){let pe=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(pe.style.color=r.contentTextColor),pe.textContent=`Duration: ${n.duration}ms`,H.appendChild(pe)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let pe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ie=ge(i?"chevron-up":"chevron-down",16,pe,2);ie?_.appendChild(ie):_.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(u,U,H),o};var rs=new Map,Ni=e=>{let n=(e.startsWith(br)?e.slice(br.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Og=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Fg=(e,t)=>{var r,o,s;let n=(o=(r=Og(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=rs.get(e))!=null?s:n==="expanded"},_g=(e,t,n)=>{var a,i;let r=Og(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=ge(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},$g=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Fg(e,n);_g(r,s,n),o.style.display=s?"":"none"};var Oi=(e,t)=>{var W,_,U,H,F,O,ee,Ee,ue,te,ve,ke,se,xe,pe;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=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(_=r==null?void 0:r.borderColor)!=null?_:"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",l=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=ge(d,20,l,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(f),!o){let ie=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ie.setAttribute("data-approval-status",n.status),n.status==="approved"?(ie.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ie.style.color="var(--persona-palette-colors-success-700, #15803d)",ie.textContent="Approved"):n.status==="denied"?(ie.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ie.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ie.textContent="Denied"):n.status==="timeout"&&(ie.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ie.style.color="var(--persona-palette-colors-warning-700, #b45309)",ie.textContent="Timeout"),g.appendChild(ie)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(br)?ra(n.toolName):void 0,M=(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,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),E=!n.toolName,P=M||(E?n.description:`The assistant wants to use \u201C${x!=null?x:Ni(n.toolName)}\u201D.`),L=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(L.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(L.style.color=r.descriptionColor),L.textContent=P,u.appendChild(L),n.reason){let ie=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ie.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?ie.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let ae=y("span","persona-font-medium");ae.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,ie.appendChild(ae),ie.appendChild(document.createTextNode(n.reason)),u.appendChild(ie)}let k=(ee=r==null?void 0:r.detailsDisplay)!=null?ee:"collapsed",I=!!n.description&&!E,C=I||!!n.parameters;if(k!=="hidden"&&C){let ie=Fg(e.id,t),ae=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");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let He=y("span");He.setAttribute("data-approval-details-label","true");let Fe=y("span","persona-inline-flex persona-items-center");Fe.setAttribute("data-approval-details-chevron","true"),ae.append(He,Fe),_g(ae,ie,t),u.appendChild(ae);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=ie?"":"none",I){let G=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(G.style.color=r.descriptionColor),G.textContent=n.description,K.appendChild(G)}if(n.parameters){let G=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&&(G.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(G.style.color=r.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=Co(n.parameters),K.appendChild(G)}u.appendChild(K)}if(o){let ie=y("div","persona-flex persona-gap-2 persona-mt-2");ie.setAttribute("data-approval-buttons","true");let ae=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");ae.type="button",ae.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(ue=r==null?void 0:r.approveButtonTextColor)!=null?ue:"#ffffff",ae.setAttribute("data-approval-action","approve");let He=ge("shield-check",14,(te=r==null?void 0:r.approveButtonTextColor)!=null?te:"#ffffff",2);He&&(He.style.marginRight="4px",ae.appendChild(He));let Fe=document.createTextNode((ve=r==null?void 0:r.approveLabel)!=null?ve:"Approve");ae.appendChild(Fe);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=(ke=r==null?void 0:r.denyButtonColor)!=null?ke:"transparent",K.style.color=(se=r==null?void 0:r.denyButtonTextColor)!=null?se:"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 G=ge("shield-x",14,(xe=r==null?void 0:r.denyButtonTextColor)!=null?xe:"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",K.appendChild(G));let we=document.createTextNode((pe=r==null?void 0:r.denyLabel)!=null?pe:"Deny");K.appendChild(we),ie.append(ae,K),u.appendChild(ie)}return a.append(i,u),s.appendChild(a),s};function hb(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 jg(e){var x;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,l=(x=e.container)!=null?x:hb(t),p=!1,u=null,g=()=>{if(!p)return;let M=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${M.width}px`);let E=r==="top-start"||r==="top-end"?M.top-o-n.getBoundingClientRect().height:M.bottom+o,P=r==="bottom-end"||r==="top-end"?M.right-n.getBoundingClientRect().width:M.left;n.style.top=`${E}px`,n.style.left=`${P}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var I,C,W;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),g();let M=(C=((I=t.ownerDocument)!=null?I:document).defaultView)!=null?C:window,E=(W=t.ownerDocument)!=null?W:document,P=()=>{if(!t.isConnected){f(),d==null||d("anchor-removed");return}g()},L=_=>{let U=typeof _.composedPath=="function"?_.composedPath():[];U.includes(n)||U.includes(t)||(f(),d==null||d("outside"))},k=M.setTimeout(()=>{E.addEventListener("pointerdown",L,!0)},0);M.addEventListener("scroll",P,!0),M.addEventListener("resize",P),u=()=>{M.clearTimeout(k),E.removeEventListener("pointerdown",L,!0),M.removeEventListener("scroll",P,!0),M.removeEventListener("resize",P)},i==null||i()};return{get isOpen(){return p},open:v,close:f,toggle:()=>p?f():v(),reposition:g,destroy:f}}function Ug(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var yb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qg=(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))},os=(e,t)=>{qg(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)},bb=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,xb=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=rs.get(e))!=null?o:n==="expanded"},tc=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},vb=(e,t)=>{var l,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(br)?ra(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:(l=e.description)!=null?l:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:Ni(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},wb=e=>{let t=y("div","persona-approval-resolved"),n=ge("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?Ni(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Cb=(e,t,n,r,o,s,a)=>{var _,U,H,F,O,ee,Ee;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=(_=r==null?void 0:r.detailsDisplay)!=null?_:"collapsed",l=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=l||p,g=u&&xb(t.id,r),f=(U=r==null?void 0:r.showDetailsLabel)!=null?U:"Show details",v=(H=r==null?void 0:r.hideDetailsLabel)!=null?H:"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",g?"true":"false"),x.setAttribute("aria-label",g?v:f)):x.setAttribute("data-static","true");let M=y("span","persona-approval-logo"),E=ge("shield-check",16,"currentColor",2);E&&M.appendChild(E),x.appendChild(M);let P=vb(n,r);if(u){let ue=y("span","persona-approval-toggle");ue.setAttribute("aria-hidden","true");let te=ge("chevron-down",14,"currentColor",2);te&&ue.appendChild(te),P.append(" "),P.appendChild(ue)}x.appendChild(P),i.appendChild(x);let L=y("div","persona-approval-body");if(u){let ue=y("div","persona-approval-details");if(ue.setAttribute("data-role","params"),ue.hidden=!g,l){let te=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=n.description,ue.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=Co(n.parameters),ue.appendChild(te)}L.appendChild(ue)}if(n.reason){let ue=y("p","persona-approval-reason");r!=null&&r.reasonColor?ue.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ue.style.color=r.descriptionColor);let te=y("span","persona-approval-reason-label");te.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,ue.append(te,document.createTextNode(n.reason)),L.appendChild(ue)}let k=y("div","persona-approval-actions"),I=null,C=ue=>{r!=null&&r.approveButtonColor&&(ue.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(ue.style.color=r.approveButtonTextColor)},W=y("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(W.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append((O=r==null?void 0:r.denyLabel)!=null?O:"Deny"),a){let ue=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",tc("\u23CE"));let ve=y("button","persona-approval-caret");ve.type="button",ve.setAttribute("data-action","toggle-menu"),ve.setAttribute("aria-label","More options"),C(ve);let ke=ge("chevron-down",15,"currentColor",2);ke&&ve.appendChild(ke),ue.append(te,ve),k.append(ue,W),W.append(tc("Esc"));let se=y("div","persona-approval-menu"),xe=y("button","persona-approval-menu-item");xe.type="button",xe.append("Allow once",tc("\u2318\u23CE")),se.appendChild(xe),I=jg({anchor:ue,content:se,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,I),xe.addEventListener("click",()=>{os(e,t.id),o()})}else{let ue=y("button","persona-approval-primary persona-approval-primary--solo");ue.type="button",ue.setAttribute("data-action","allow"),C(ue),ue.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),k.append(ue,W)}return L.appendChild(k),i.appendChild(L),i.addEventListener("click",ue=>{let te=ue.target instanceof Element?ue.target.closest("[data-action]"):null;if(!te)return;let ve=te.getAttribute("data-action");if(ve==="toggle-params"){let ke=i.querySelector('[data-role="params"]');if(ke){let se=ke.hidden;ke.hidden=!se,x.setAttribute("aria-expanded",se?"true":"false"),x.setAttribute("aria-label",se?v:f),rs.set(t.id,se)}return}if(ve==="toggle-menu"){I==null||I.toggle();return}if(ve==="always"){os(e,t.id),o({remember:!0});return}if(ve==="allow"){os(e,t.id),o();return}if(ve==="deny"){os(e,t.id),s();return}}),i},zg=()=>{let e=yb();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=bb(a);if(i.status!=="pending"){if(os(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return wb(i)}qg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=Cb(e,r,i,d,o,s,l);if(l){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{Ug(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),os(e,r.id),g.key==="Escape"?s():g.metaKey||g.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()])os(e,r);e.latestPendingApprovalId=null}}};var Vg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let u=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=v=>{switch(v){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(v=>{let x=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");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),t.push(x)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ka=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 La=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 Ab=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Sb=new Set(["step_start","execution_start"]),Tb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Eb=new Set(["step_complete","agent_turn_complete"]),Mb=new Set(["flow_complete","agent_complete"]),Kg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ss=(e,t)=>{let n=e[t];return Jg(n)?n:void 0};function nc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function kb(e,t){return typeof t.type=="string"?t.type:e}function Lb(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 Pb(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Gg(e){var r,o,s,a,i;let t=ss(e,"result"),n=[ss(e,"tokens"),ss(e,"totalTokens"),t?ss(t,"tokens"):void 0,ss(e,"usage"),t?ss(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Yn(d.output))!=null?r:Yn(d.outputTokens))!=null?o:Yn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Yn(e.outputTokens))!=null?s:Yn(e.completionTokens))!=null?i:t?(a=Yn(t.outputTokens))!=null?a:Yn(t.completionTokens):void 0}function Ib(e){var n,r,o,s,a;let t=ss(e,"result");return(a=(o=(r=(n=Yn(e.executionTime))!=null?n:Yn(e.executionTimeMs))!=null?r:Yn(e.execution_time))!=null?o:Yn(e.duration))!=null?a:t?(s=Yn(t.executionTime))!=null?s:Yn(t.executionTimeMs):void 0}function Rb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Pa=class{constructor(t=Rb){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:Fi(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(!Jg(n)){Kg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=kb(t,n),o=this.now();if(Ab.has(r)){this.startRun(o);return}if(Sb.has(r)){this.run||this.startRun(o);return}if(Tb.has(r)){if(!Pb(r,n))return;let a=Lb(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+nc(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Eb.has(r)){if(!this.run)return;let a=this.run,i=Gg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+nc(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Mb.has(r)){if(!this.run)return;let a=this.run,i=Gg(n),d=i!=null?i:a.exactOutputTokens+nc(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Kg.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=Ib(n);return s!=null?s:r-t.startedAt}};function _s(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Wb={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)"}},Hb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Bb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Db=100;function Nb(e,t){let n={...Wb,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Hb}function Ob(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Fb(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 _b(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 $b(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 jb(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Ub(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function qb(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function zb(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 rc(e,t,n,r,o,s,a,i){var g;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");_s(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var O,ee;let f=y("div",""),v=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");v.setAttribute("data-event-id",e.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&x.appendChild(M);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=(O=r.timestampFormat)!=null?O:"relative";E.textContent=P==="relative"?Ob(e.timestamp,n):Fb(e.timestamp);let L=null;r.showSequenceNumbers!==!1&&(L=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let k=Nb(e.type,r.badgeColors),I=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");I.style.backgroundColor=k.bg,I.style.color=k.text,I.style.borderColor=k.text+"50",I.textContent=e.type;let C=(ee=r.descriptionFields)!=null?ee:Bb,W=_b(e.payload,C),_=null;W&&(_=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=W);let U=y("div","persona-flex-1 persona-min-w-0"),H=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"),F=ge("clipboard","12px","currentColor",1.5);return F&&H.appendChild(F),H.addEventListener("click",async Ee=>{Ee.stopPropagation(),await $b(jb(e)),H.innerHTML="";let ue=ge("check","12px","currentColor",1.5);ue&&H.appendChild(ue),setTimeout(()=>{H.innerHTML="";let te=ge("clipboard","12px","currentColor",1.5);te&&H.appendChild(te)},1500)}),v.appendChild(x),v.appendChild(E),L&&v.appendChild(L),v.appendChild(I),_&&v.appendChild(_),v.appendChild(U),v.appendChild(H),f.appendChild(v),d&&f.appendChild(zb(e,a,i)),f}}function Xg(e){var v,x,M,E,P;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",u=(P=(E=o==null?void 0:o.features)==null?void 0:E.eventStream)!=null?P:{},g=s.find(L=>L.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let L=g.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=u.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");_s(k,L==null?void 0:L.panel);let I=[],C="",W="",_=null,U=[],H={},F=0,O=wi(),ee=0,Ee=0,ue=!1,te=null,ve=!1,ke=0,se=new Set,xe=new Map,pe="",ie="",ae=null,He,Fe,K,G,we,X=null,de=null,We=null;function fe(){let B=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Y=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");_s(Y,L==null?void 0:L.headerBar);let Te=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Te.textContent="Events",He=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"),He.textContent="0",a){de=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),de.style.cursor="help";let $t=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");$t.textContent="Throughput",X=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"),X.textContent="-- tok/s",We=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"),We.style.display="none",We.style.pointerEvents="none";let On=de,Tn=We,En=()=>{if(!Tn.textContent)return;let Mn=On.getBoundingClientRect(),dr=B.getBoundingClientRect();Tn.style.left=`${Mn.left-dr.left}px`,Tn.style.top=`${Mn.bottom-dr.top+4}px`,Tn.style.display="block"},vn=()=>{Tn.style.display="none"};de.addEventListener("mouseenter",En),de.addEventListener("mouseleave",vn),de.appendChild($t),de.appendChild(X)}let ct=y("div","persona-flex-1");Fe=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 Ye=y("option","");Ye.value="",Ye.textContent="All events",Fe.appendChild(Ye),K=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let bn=ge("clipboard-copy","12px","currentColor",1.5);bn&&K.appendChild(bn);let vt=y("span","persona-text-xs");vt.textContent="Copy All",K.appendChild(vt),Y.appendChild(Te),Y.appendChild(He),de&&Y.appendChild(de),Y.appendChild(ct),Y.appendChild(Fe),Y.appendChild(K);let wt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");_s(wt,L==null?void 0:L.searchBar);let Rt=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),Ct=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");Rt&&Ct.appendChild(Rt),G=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"),_s(G,L==null?void 0:L.searchInput),G.type="text",G.placeholder="Search event payloads...",we=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"),we.type="button",we.style.display="none";let pn=ge("x","12px","currentColor",2);return pn&&we.appendChild(pn),wt.appendChild(Ct),wt.appendChild(G),wt.appendChild(we),B.appendChild(Y),B.appendChild(wt),We&&B.appendChild(We),B}let Ge,nt=s.find(B=>B.renderEventStreamToolbar);if(nt!=null&&nt.renderEventStreamToolbar&&o){let B=nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>fe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Y=>{C=Y,je(),Yt()},onSearchChange:Y=>{W=Y,je(),Yt()}});Ge=B!=null?B:fe()}else Ge=fe();let Pt=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");Pt.style.display="none";function Ze(){if(!a||!X||!de)return;let B=a();X.textContent=Ub(B);let Y=qb(B);We&&(We.textContent=Y,Y||(We.style.display="none")),Y?de.setAttribute("aria-label",Y):de.removeAttribute("aria-label")}let $e=y("div","persona-flex-1 persona-min-h-0 persona-relative"),J=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let Ve=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");_s(Ve,L==null?void 0:L.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let ze=ge(l,"14px","currentColor",2);ze&&Ve.appendChild(ze);let Ce=y("span","");Ce.textContent=p,Ve.appendChild(Ce);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",$e.appendChild(J),$e.appendChild(Se),$e.appendChild(Ve),k.setAttribute("tabindex","0"),k.appendChild(Ge),k.appendChild(Pt),k.appendChild($e);function rt(){let B=t.getAll(),Y={};for(let vt of B)Y[vt.type]=(Y[vt.type]||0)+1;let Te=Object.keys(Y).sort(),ct=Te.length!==U.length||!Te.every((vt,wt)=>vt===U[wt]),Ye=!ct&&Te.some(vt=>Y[vt]!==H[vt]),Ut=B.length!==Object.values(H).reduce((vt,wt)=>vt+wt,0);if(!ct&&!Ye&&!Ut||(U=Te,H=Y,!Fe))return;let bn=Fe.value;if(Fe.options[0].textContent="All events",ct){for(;Fe.options.length>1;)Fe.remove(1);for(let vt of Te){let wt=y("option","");wt.value=vt,wt.textContent=`${vt} (${Y[vt]||0})`,Fe.appendChild(wt)}bn&&Te.includes(bn)?Fe.value=bn:bn&&(Fe.value="",C="")}else for(let vt=1;vt<Fe.options.length;vt++){let wt=Fe.options[vt];wt.textContent=`${wt.value} (${Y[wt.value]||0})`}}function _t(){let B=t.getAll();if(C&&(B=B.filter(Y=>Y.type===C)),W){let Y=W.toLowerCase();B=B.filter(Te=>Te.type.toLowerCase().includes(Y)||Te.payload.toLowerCase().includes(Y))}return B}function re(){return C!==""||W!==""}function je(){F=0,ee=0,O.resume(),Ve.style.display="none"}function yn(B){se.has(B)?se.delete(B):se.add(B),ae=B;let Y=J.scrollTop,Te=O.isFollowing();ve=!0,O.pause(),Yt(),J.scrollTop=Y,Te&&O.resume(),ve=!1}function Dt(){return es(J,50)}function Yt(){Ee=Date.now(),ue=!1,Ze(),rt();let B=t.getEvictedCount();B>0?(Pt.textContent=`${B.toLocaleString()} older events truncated`,Pt.style.display=""):Pt.style.display="none",I=_t();let Y=I.length,Te=t.getSize()>0;He&&(He.textContent=String(t.getSize())),Y===0&&Te&&re()?(Se.textContent=W?`No events matching '${W}'`:"No events matching filter",Se.style.display="",J.style.display="none"):(Se.style.display="none",J.style.display=""),K&&(K.title=re()?`Copy Filtered (${Y})`:"Copy All"),d&&!O.isFollowing()&&Y>F&&(ee+=Y-F,Ce.textContent=p?`${p}${ee>0?` (${ee})`:""}`:"",Ve.style.display=""),F=Y;let ct=t.getAll(),Ye=ct.length>0?ct[0].timestamp:0,Ut=new Set(I.map(wt=>wt.id));for(let wt of se)Ut.has(wt)||se.delete(wt);let bn=C!==pe||W!==ie,vt=xe.size===0&&I.length>0;if(bn||vt||I.length===0){J.innerHTML="",xe.clear();let wt=document.createDocumentFragment();for(let Rt=0;Rt<I.length;Rt++){let Ct=rc(I[Rt],Rt,Ye,u,se,yn,s,o);xe.set(I[Rt].id,Ct),wt.appendChild(Ct)}J.appendChild(wt),pe=C,ie=W,ae=null}else{if(ae!==null){let Rt=xe.get(ae);if(Rt&&Rt.parentNode===J){let Ct=I.findIndex(pn=>pn.id===ae);if(Ct>=0){let pn=rc(I[Ct],Ct,Ye,u,se,yn,s,o);J.insertBefore(pn,Rt),Rt.remove(),xe.set(ae,pn)}}ae=null}let wt=new Set(I.map(Rt=>Rt.id));for(let[Rt,Ct]of xe)wt.has(Rt)||(Ct.remove(),xe.delete(Rt));for(let Rt=0;Rt<I.length;Rt++){let Ct=I[Rt];if(!xe.has(Ct.id)){let pn=rc(Ct,Rt,Ye,u,se,yn,s,o);xe.set(Ct.id,pn),J.appendChild(pn)}}}O.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Or(){if(Date.now()-Ee>=Db){te!==null&&(cancelAnimationFrame(te),te=null),Yt();return}ue||(ue=!0,te=requestAnimationFrame(()=>{te=null,Yt()}))}let wr=(B,Y)=>{if(!K)return;K.innerHTML="";let Te=ge(B,"12px","currentColor",1.5);Te&&K.appendChild(Te);let ct=y("span","persona-text-xs");ct.textContent="Copy All",K.appendChild(ct),setTimeout(()=>{K.innerHTML="";let Ye=ge("clipboard-copy","12px","currentColor",1.5);Ye&&K.appendChild(Ye);let Ut=y("span","persona-text-xs");Ut.textContent="Copy All",K.appendChild(Ut),K.disabled=!1},Y)},S=async()=>{if(K){K.disabled=!0;try{let B;re()?B=I:n?(B=await n(),B.length===0&&(B=t.getAll())):B=t.getAll();let Y=B.map(Te=>{try{return JSON.parse(Te.payload)}catch{return Te.payload}});await navigator.clipboard.writeText(JSON.stringify(Y,null,2)),wr("check",1500)}catch{wr("x",1500)}}},ne=()=>{Fe&&(C=Fe.value,je(),Yt())},Me=()=>{!G||!we||(we.style.display=G.value?"":"none",_&&clearTimeout(_),_=setTimeout(()=>{W=G.value,je(),Yt()},150))},De=()=>{!G||!we||(G.value="",W="",we.style.display="none",_&&clearTimeout(_),je(),Yt())},Pe=()=>{if(ve)return;let B=J.scrollTop,{action:Y,nextLastScrollTop:Te}=Ci({following:O.isFollowing(),currentScrollTop:B,lastScrollTop:ke,nearBottom:Dt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ke=Te,Y==="resume"?(O.resume(),ee=0,Ve.style.display="none"):Y==="pause"&&(O.pause(),d&&(Ce.textContent=p,Ve.style.display=""))},Ne=B=>{let Y=Ai({following:O.isFollowing(),deltaY:B.deltaY,nearBottom:Dt(),resumeWhenNearBottom:!0});Y==="pause"?(O.pause(),d&&(Ce.textContent=p,Ve.style.display="")):Y==="resume"&&(O.resume(),ee=0,Ve.style.display="none")},Je=()=>{d&&(J.scrollTop=J.scrollHeight,O.resume(),ee=0,Ve.style.display="none")},lt=B=>{let Y=B.target;if(!Y||Y.closest("button"))return;let Te=Y.closest("[data-event-id]");if(!Te)return;let ct=Te.getAttribute("data-event-id");ct&&yn(ct)},It=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),G==null||G.focus(),G==null||G.select();return}B.key==="Escape"&&(G&&document.activeElement===G?(De(),G.blur(),k.focus()):r&&r())};K&&K.addEventListener("click",S),Fe&&Fe.addEventListener("change",ne),G&&G.addEventListener("input",Me),we&&we.addEventListener("click",De),J.addEventListener("scroll",Pe),J.addEventListener("wheel",Ne,{passive:!0}),J.addEventListener("click",lt),Ve.addEventListener("click",Je),k.addEventListener("keydown",It);function xt(){_&&clearTimeout(_),te!==null&&(cancelAnimationFrame(te),te=null),ue=!1,xe.clear(),K&&K.removeEventListener("click",S),Fe&&Fe.removeEventListener("change",ne),G&&G.removeEventListener("input",Me),we&&we.removeEventListener("click",De),J.removeEventListener("scroll",Pe),J.removeEventListener("wheel",Ne),J.removeEventListener("click",lt),Ve.removeEventListener("click",Je),k.removeEventListener("keydown",It)}return{element:k,update:Or,destroy:xt}}}function Qg(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 l=document.createElement("div");l.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 g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Yg=(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",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Qg(e,t)});if(p)return p}return Qg(e,t)};var oc=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)})}},to=new oc;to.register("PersonaArtifactCard",Yg);function Vb(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 Zg(e,t){var Fe,K,G,we;let n=(K=(Fe=e.features)==null?void 0:Fe.artifacts)==null?void 0:K.layout,o=((G=n==null?void 0:n.toolbarPreset)!=null?G:"default")==="document",s=(we=n==null?void 0:n.panePadding)==null?void 0:we.trim(),a=e.markdown?Ko(e.markdown):null,i=As(e.sanitize),d=X=>{let de=a?a(X):Br(X);return i?i(de):de},l=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=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.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 g=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let v=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let x="rendered",M=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"}),L=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),k=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(I&&C&&C.length>0),_=null,U,H=null,F=null;if(o&&(k||I)&&!W){if(U=k?Ea({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=ge("chevron-down",14,"currentColor",2);X&&U.appendChild(X)}}else o&&W?(_=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),U=k?Ea({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=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"}}),_.append(U,H)):o?U=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):U=Gt({icon:"copy",label:"Copy"});let O=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"}),Ee=()=>{var Ge,nt,Pt;let X=(Ge=xe.find(Ze=>Ze.id===pe))!=null?Ge:xe[xe.length-1],de=(nt=X==null?void 0:X.id)!=null?nt:null,We=(X==null?void 0:X.artifactType)==="markdown"&&(Pt=X.markdown)!=null?Pt:"",fe=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:We,jsonPayload:fe,id:de}},ue=async()=>{var Ge;let{markdown:X,jsonPayload:de}=Ee(),We=(Ge=xe.find(nt=>nt.id===pe))!=null?Ge:xe[xe.length-1],fe=(We==null?void 0:We.artifactType)==="markdown"?X:We?de:"";try{await navigator.clipboard.writeText(fe)}catch{}};if(U.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&W){let{markdown:de,jsonPayload:We,id:fe}=Ee();try{await X({actionId:"primary",artifactId:fe,markdown:de,jsonPayload:We})}catch{}return}await ue()}),H&&(C!=null&&C.length)){let X=()=>{var We;return(We=u.closest("[data-persona-root]"))!=null?We:document.body},de=()=>{F=Lo({items:C.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:fe,jsonPayload:Ge,id:nt}=Ee(),Pt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Pt?await Pt({actionId:We,artifactId:nt,markdown:fe,jsonPayload:Ge}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(fe):We==="json"||We==="source"?await navigator.clipboard.writeText(Ge):await navigator.clipboard.writeText(fe||Ge)}catch{}},anchor:_!=null?_:H,position:"bottom-right",portal:X()})};u.isConnected?de():requestAnimationFrame(de),H.addEventListener("click",We=>{We.stopPropagation(),F==null||F.toggle()})}O.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}ae()}),ee.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let te=()=>{o&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),P.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",te(),ae()}),P.addEventListener("click",()=>{x="source",te(),ae()});let ve=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?(g.replaceChildren(),M.append(E,P),_?L.append(_,O,ee):L.append(U,O,ee),g.append(M,ve,L),te()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let ke=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"),se=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ke.style.paddingLeft=s,ke.style.paddingRight=s,se.style.padding=s),u.appendChild(g),u.appendChild(ke),u.appendChild(se);let xe=[],pe=null,ie=!1,ae=()=>{var fe,Ge,nt,Pt;let X=o&&xe.length<=1;ke.classList.toggle("persona-hidden",X),ke.replaceChildren();for(let Ze of xe){let $e=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");$e.type="button",$e.textContent=Ze.title||Ze.id.slice(0,8),Ze.id===pe&&$e.classList.add("persona-bg-persona-container","persona-border-persona-border"),$e.addEventListener("click",()=>t.onSelect(Ze.id)),ke.appendChild($e)}se.replaceChildren();let de=pe&&xe.find(Ze=>Ze.id===pe)||xe[xe.length-1];if(!de)return;if(o){let Ze=de.artifactType==="markdown"?"MD":(fe=de.component)!=null?fe:"Component",J=(de.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${J} \xB7 ${Ze}`}else f.textContent="Artifacts";if(de.artifactType==="markdown"){if(o&&x==="source"){let $e=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");$e.textContent=(Ge=de.markdown)!=null?Ge:"",se.appendChild($e);return}let Ze=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ze.innerHTML=d((nt=de.markdown)!=null?nt:""),se.appendChild(Ze);return}let We=de.component?to.get(de.component):void 0;if(We){let $e={message:{id:de.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=We((Pt=de.props)!=null?Pt:{},$e);if(J){se.appendChild(J);return}}catch{}}se.appendChild(Vb(de))},He=()=>{var de;let X=xe.length>0;if(u.classList.toggle("persona-hidden",!X),l){let We=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ge=((de=We==null?void 0:We.classList.contains("persona-artifact-narrow-host"))!=null?de:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&Ge&&ie?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(X){var de,We,fe;xe=X.artifacts,pe=(fe=(We=X.selectedId)!=null?We:(de=X.artifacts[X.artifacts.length-1])==null?void 0:de.id)!=null?fe:null,xe.length>0&&(ie=!0),ae(),He()},setMobileOpen(X){ie=X,!X&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):He()}}}function cr(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 ef(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"),!cr(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 Kb(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 _i(e,t){var d,l,p,u,g,f,v,x,M,E;if(!cr(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"),Kb(e),ef(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.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",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.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"),ef(e,t)}var tf=["panel","seamless"];function $i(e,t){var i,d,l,p,u,g;for(let f of tf)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!cr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",o=tf.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 f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function nf(e,t){var n,r,o;return!t||!cr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Gb(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 Jb(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 Xb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Qb(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function rf(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 of(e,t,n,r,o,s){let a=Gb(o,200),i=Qb(t,n,r,200);i=Math.max(a,i);let d=Jb(s);return d!==null&&(i=Math.min(i,d)),Xb(e,a,i)}var sf={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"}},sc=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,M;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=sf[a])!=null?x:sf.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),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,W;let P=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");P.htmlFor=`${t.id}-${a}-${E.name}`;let L=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=E.label,P.appendChild(L);let k=(C=E.type)!=null?C:"text",I;k==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=k),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=(W=E.placeholder)!=null?W:"",E.required&&(I.required=!0),P.appendChild(I),p.appendChild(P)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async E=>{var I,C;E.preventDefault();let P=(I=n.formEndpoint)!=null?I:"/form",L=new FormData(p),k={};L.forEach((W,_)=>{k[_]=W}),k.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let _=await W.json();g.textContent=(C=_.message)!=null?C:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ac=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()}},Ia=new ac;var af=()=>{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 Yb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Zb=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},Ra=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Yb(e),n=Zb(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}},ic=e=>typeof e=="string"?e:e==null?"":String(e),as={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ic(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=ic(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:ic(n.text)}}},lf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Wa=e=>{let t=new Set(lf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(lf(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((l,p)=>l||(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 l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var ex=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}},tx=e=>e.map(t=>({...t,streaming:!1})),nx=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?ex(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?tx(n.messages):void 0,artifacts:n.artifacts?nx(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 $s=require("partial-json");function rx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function ox(e,t){if(!rx(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 Ui(){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,$s.parse)(n,$s.STR|$s.OBJ),s=ox(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function cf(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=to.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=Ui();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function pf(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 zi(e){let t=pf(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 Vi(e){let t=pf(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 sx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ki(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:l=sx}=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,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,f.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,f.appendChild(x),g.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let C=1;C<=5;C++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),W.title=l[C-1],W.dataset.rating=String(C),W.innerHTML=`
|
|
30
|
+
`):""},Zl=(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)"},fb=(e,t)=>{var p,u,g,f,v;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=gb(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Hm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=kl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=kl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Ng=(e,t,n)=>{var p;let r=Fs.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"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=ge(r?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},ec=(e,t)=>{var O,Z,Me,pe,ee,Ae,Le,oe,Ce;let n=e.toolCall,r=(O=t==null?void 0:t.toolCall)!=null?O:{},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=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Me:{},a=s.expandable!==!1,i=a&&Fs.has(e.id),{summary:d,previewText:l,isActive:p}=fb(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 g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let v=String((pe=n.startedAt)!=null?pe:Date.now()),x=()=>{let ce=y("span","");return ce.setAttribute("data-tool-elapsed",v),ce.textContent=pa(n),ce},M=(Ae=r.renderCollapsedSummary)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:pa(n),createElapsedElement:x});typeof M=="string"&&M.trim()?(f.textContent=M,g.appendChild(f)):M instanceof HTMLElement?g.appendChild(M):(f.textContent=d,g.appendChild(f));let E=(Le=s.loadingAnimation)!=null?Le:"none",P=r.activeTextTemplate,L=r.completeTextTemplate,k=p?P:L,I=M instanceof HTMLElement,C=(ce,ae,se)=>{let xe=se;for(let Be of ae){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(xe)),K.textContent=Be===" "?"\xA0":Be,ce.appendChild(K),xe++}return xe},W=(ce,ae)=>{var K;f.textContent="";let se=((K=n.name)==null?void 0:K.trim())||"tool",xe=ni(ce,se),Be=0;for(let Q of xe){let He=Q.styles.length>0?(()=>{let G=y("span",Q.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return f.appendChild(G),G})():f;if(Q.isDuration&&p)He.appendChild(x());else{let G=Q.isDuration?pa(n):Q.text;ae?Be=C(He,G,Be):He.appendChild(document.createTextNode(G))}}};if(!I)if(p&&E!=="none"){let ce=(oe=r.loadingAnimationDuration)!=null?oe:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),k&&W(k,!1);else if(f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),E==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)W(k,!0);else{let ae=f.textContent||d;f.textContent="",C(f,ae,0)}}else k&&W(k,!1);let _=null;if(a){_=y("div","persona-flex persona-items-center");let ce=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=ge(i?"chevron-up":"chevron-down",16,ce,2);ae?_.appendChild(ae):_.textContent=i?"Hide":"Show";let se=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(_),u.append(g,se)}else u.append(g);let U=y("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&&l){let ce=(Ce=r.renderCollapsedPreview)==null?void 0:Ce.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});mb(U,ce)||(U.textContent=l),U.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,U),o;let H=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let ce=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ce.style.color=r.contentTextColor:r.headerTextColor&&(ce.style.color=r.headerTextColor),ce.textContent=n.name,H.appendChild(ce)}if(n.args!==void 0){let ce=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 se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Zl(se,r),se.textContent=Co(n.args),ce.append(ae,se),H.appendChild(ce)}if(n.chunks&&n.chunks.length){let ce=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 se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Zl(se,r),se.textContent=n.chunks.join(""),ce.append(ae,se),H.appendChild(ce)}if(n.status==="complete"&&n.result!==void 0){let ce=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 se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Zl(se,r),se.textContent=Co(n.result),ce.append(ae,se),H.appendChild(ce)}if(n.status==="complete"&&typeof n.duration=="number"){let ce=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ce.style.color=r.contentTextColor),ce.textContent=`Duration: ${n.duration}ms`,H.appendChild(ce)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let ce=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=ge(i?"chevron-up":"chevron-down",16,ce,2);ae?_.appendChild(ae):_.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(u,U,H),o};var rs=new Map,Ni=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)},Og=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Fg=(e,t)=>{var r,o,s;let n=(o=(r=Og(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=rs.get(e))!=null?s:n==="expanded"},_g=(e,t,n)=>{var a,i;let r=Og(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=ge(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},$g=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Fg(e,n);_g(r,s,n),o.style.display=s?"":"none"};var Oi=(e,t)=>{var W,_,U,H,F,O,Z,Me,pe,ee,Ae,Le,oe,Ce,ce;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=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(_=r==null?void 0:r.borderColor)!=null?_:"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",l=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=ge(d,20,l,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(f),!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"),g.appendChild(ae)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(yr)?ra(n.toolName):void 0,M=(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,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),E=!n.toolName,P=M||(E?n.description:`The assistant wants to use \u201C${x!=null?x:Ni(n.toolName)}\u201D.`),L=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(L.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(L.style.color=r.descriptionColor),L.textContent=P,u.appendChild(L),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 se=y("span","persona-font-medium");se.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,ae.appendChild(se),ae.appendChild(document.createTextNode(n.reason)),u.appendChild(ae)}let k=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",I=!!n.description&&!E,C=I||!!n.parameters;if(k!=="hidden"&&C){let ae=Fg(e.id,t),se=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");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let xe=y("span");xe.setAttribute("data-approval-details-label","true");let Be=y("span","persona-inline-flex persona-items-center");Be.setAttribute("data-approval-details-chevron","true"),se.append(xe,Be),_g(se,ae,t),u.appendChild(se);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=ae?"":"none",I){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor),Q.textContent=n.description,K.appendChild(Q)}if(n.parameters){let Q=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&&(Q.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Q.style.color=r.parameterTextColor),Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Q.textContent=Co(n.parameters),K.appendChild(Q)}u.appendChild(K)}if(o){let ae=y("div","persona-flex persona-gap-2 persona-mt-2");ae.setAttribute("data-approval-buttons","true");let se=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");se.type="button",se.style.backgroundColor=(Me=r==null?void 0:r.approveButtonColor)!=null?Me:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",se.setAttribute("data-approval-action","approve");let xe=ge("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);xe&&(xe.style.marginRight="4px",se.appendChild(xe));let Be=document.createTextNode((Ae=r==null?void 0:r.approveLabel)!=null?Ae:"Approve");se.appendChild(Be);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=(Le=r==null?void 0:r.denyButtonColor)!=null?Le:"transparent",K.style.color=(oe=r==null?void 0:r.denyButtonTextColor)!=null?oe:"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 Q=ge("shield-x",14,(Ce=r==null?void 0:r.denyButtonTextColor)!=null?Ce:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",K.appendChild(Q));let He=document.createTextNode((ce=r==null?void 0:r.denyLabel)!=null?ce:"Deny");K.appendChild(He),ae.append(se,K),u.appendChild(ae)}return a.append(i,u),s.appendChild(a),s};function hb(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 jg(e){var x;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,l=(x=e.container)!=null?x:hb(t),p=!1,u=null,g=()=>{if(!p)return;let M=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${M.width}px`);let E=r==="top-start"||r==="top-end"?M.top-o-n.getBoundingClientRect().height:M.bottom+o,P=r==="bottom-end"||r==="top-end"?M.right-n.getBoundingClientRect().width:M.left;n.style.top=`${E}px`,n.style.left=`${P}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var I,C,W;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),g();let M=(C=((I=t.ownerDocument)!=null?I:document).defaultView)!=null?C:window,E=(W=t.ownerDocument)!=null?W:document,P=()=>{if(!t.isConnected){f(),d==null||d("anchor-removed");return}g()},L=_=>{let U=typeof _.composedPath=="function"?_.composedPath():[];U.includes(n)||U.includes(t)||(f(),d==null||d("outside"))},k=M.setTimeout(()=>{E.addEventListener("pointerdown",L,!0)},0);M.addEventListener("scroll",P,!0),M.addEventListener("resize",P),u=()=>{M.clearTimeout(k),E.removeEventListener("pointerdown",L,!0),M.removeEventListener("scroll",P,!0),M.removeEventListener("resize",P)},i==null||i()};return{get isOpen(){return p},open:v,close:f,toggle:()=>p?f():v(),reposition:g,destroy:f}}function Ug(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var yb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qg=(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))},os=(e,t)=>{qg(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)},bb=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,xb=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=rs.get(e))!=null?o:n==="expanded"},tc=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},vb=(e,t)=>{var l,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)?ra(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:(l=e.description)!=null?l:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:Ni(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},wb=e=>{let t=y("div","persona-approval-resolved"),n=ge("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?Ni(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Cb=(e,t,n,r,o,s,a)=>{var _,U,H,F,O,Z,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=(_=r==null?void 0:r.detailsDisplay)!=null?_:"collapsed",l=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=l||p,g=u&&xb(t.id,r),f=(U=r==null?void 0:r.showDetailsLabel)!=null?U:"Show details",v=(H=r==null?void 0:r.hideDetailsLabel)!=null?H:"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",g?"true":"false"),x.setAttribute("aria-label",g?v:f)):x.setAttribute("data-static","true");let M=y("span","persona-approval-logo"),E=ge("shield-check",16,"currentColor",2);E&&M.appendChild(E),x.appendChild(M);let P=vb(n,r);if(u){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=ge("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),P.append(" "),P.appendChild(pe)}x.appendChild(P),i.appendChild(x);let L=y("div","persona-approval-body");if(u){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,l){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,pe.appendChild(ee)}if(p){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=Co(n.parameters),pe.appendChild(ee)}L.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 ee=y("span","persona-approval-reason-label");ee.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(n.reason)),L.appendChild(pe)}let k=y("div","persona-approval-actions"),I=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},W=y("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(W.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append((O=r==null?void 0:r.denyLabel)!=null?O:"Deny"),a){let pe=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",tc("\u23CE"));let Ae=y("button","persona-approval-caret");Ae.type="button",Ae.setAttribute("data-action","toggle-menu"),Ae.setAttribute("aria-label","More options"),C(Ae);let Le=ge("chevron-down",15,"currentColor",2);Le&&Ae.appendChild(Le),pe.append(ee,Ae),k.append(pe,W),W.append(tc("Esc"));let oe=y("div","persona-approval-menu"),Ce=y("button","persona-approval-menu-item");Ce.type="button",Ce.append("Allow once",tc("\u2318\u23CE")),oe.appendChild(Ce),I=jg({anchor:pe,content:oe,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,I),Ce.addEventListener("click",()=>{os(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"),k.append(pe,W)}return L.appendChild(k),i.appendChild(L),i.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let Ae=ee.getAttribute("data-action");if(Ae==="toggle-params"){let Le=i.querySelector('[data-role="params"]');if(Le){let oe=Le.hidden;Le.hidden=!oe,x.setAttribute("aria-expanded",oe?"true":"false"),x.setAttribute("aria-label",oe?v:f),rs.set(t.id,oe)}return}if(Ae==="toggle-menu"){I==null||I.toggle();return}if(Ae==="always"){os(e,t.id),o({remember:!0});return}if(Ae==="allow"){os(e,t.id),o();return}if(Ae==="deny"){os(e,t.id),s();return}}),i},zg=()=>{let e=yb();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=bb(a);if(i.status!=="pending"){if(os(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return wb(i)}qg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=Cb(e,r,i,d,o,s,l);if(l){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{Ug(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),os(e,r.id),g.key==="Escape"?s():g.metaKey||g.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()])os(e,r);e.latestPendingApprovalId=null}}};var Vg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let u=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=v=>{switch(v){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(v=>{let x=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");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),t.push(x)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ka=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 La=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 Ab=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Sb=new Set(["step_start","execution_start"]),Tb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Eb=new Set(["step_complete","agent_turn_complete"]),Mb=new Set(["flow_complete","agent_complete"]),Kg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ss=(e,t)=>{let n=e[t];return Jg(n)?n:void 0};function nc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function kb(e,t){return typeof t.type=="string"?t.type:e}function Lb(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 Pb(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Gg(e){var r,o,s,a,i;let t=ss(e,"result"),n=[ss(e,"tokens"),ss(e,"totalTokens"),t?ss(t,"tokens"):void 0,ss(e,"usage"),t?ss(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Xn(d.output))!=null?r:Xn(d.outputTokens))!=null?o:Xn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Xn(e.outputTokens))!=null?s:Xn(e.completionTokens))!=null?i:t?(a=Xn(t.outputTokens))!=null?a:Xn(t.completionTokens):void 0}function Ib(e){var n,r,o,s,a;let t=ss(e,"result");return(a=(o=(r=(n=Xn(e.executionTime))!=null?n:Xn(e.executionTimeMs))!=null?r:Xn(e.execution_time))!=null?o:Xn(e.duration))!=null?a:t?(s=Xn(t.executionTime))!=null?s:Xn(t.executionTimeMs):void 0}function Rb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Pa=class{constructor(t=Rb){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:Fi(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(!Jg(n)){Kg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=kb(t,n),o=this.now();if(Ab.has(r)){this.startRun(o);return}if(Sb.has(r)){this.run||this.startRun(o);return}if(Tb.has(r)){if(!Pb(r,n))return;let a=Lb(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+nc(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Eb.has(r)){if(!this.run)return;let a=this.run,i=Gg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+nc(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Mb.has(r)){if(!this.run)return;let a=this.run,i=Gg(n),d=i!=null?i:a.exactOutputTokens+nc(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Kg.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=Ib(n);return s!=null?s:r-t.startedAt}};function _s(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Wb={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)"}},Hb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Bb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Db=100;function Nb(e,t){let n={...Wb,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Hb}function Ob(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Fb(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 _b(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 $b(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 jb(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Ub(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function qb(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function zb(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 rc(e,t,n,r,o,s,a,i){var g;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");_s(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var O,Z;let f=y("div",""),v=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");v.setAttribute("data-event-id",e.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&x.appendChild(M);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=(O=r.timestampFormat)!=null?O:"relative";E.textContent=P==="relative"?Ob(e.timestamp,n):Fb(e.timestamp);let L=null;r.showSequenceNumbers!==!1&&(L=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let k=Nb(e.type,r.badgeColors),I=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");I.style.backgroundColor=k.bg,I.style.color=k.text,I.style.borderColor=k.text+"50",I.textContent=e.type;let C=(Z=r.descriptionFields)!=null?Z:Bb,W=_b(e.payload,C),_=null;W&&(_=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=W);let U=y("div","persona-flex-1 persona-min-w-0"),H=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"),F=ge("clipboard","12px","currentColor",1.5);return F&&H.appendChild(F),H.addEventListener("click",async Me=>{Me.stopPropagation(),await $b(jb(e)),H.innerHTML="";let pe=ge("check","12px","currentColor",1.5);pe&&H.appendChild(pe),setTimeout(()=>{H.innerHTML="";let ee=ge("clipboard","12px","currentColor",1.5);ee&&H.appendChild(ee)},1500)}),v.appendChild(x),v.appendChild(E),L&&v.appendChild(L),v.appendChild(I),_&&v.appendChild(_),v.appendChild(U),v.appendChild(H),f.appendChild(v),d&&f.appendChild(zb(e,a,i)),f}}function Xg(e){var v,x,M,E,P;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",u=(P=(E=o==null?void 0:o.features)==null?void 0:E.eventStream)!=null?P:{},g=s.find(L=>L.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let L=g.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=u.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");_s(k,L==null?void 0:L.panel);let I=[],C="",W="",_=null,U=[],H={},F=0,O=wi(),Z=0,Me=0,pe=!1,ee=null,Ae=!1,Le=0,oe=new Set,Ce=new Map,ce="",ae="",se=null,xe,Be,K,Q,He=null,G=null,ue=null;function je(){let de=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=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(_s(B,L==null?void 0:L.headerBar),a){G=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),G.style.cursor="help",He=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"),He.textContent="-- tok/s",ue=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"),ue.style.display="none",ue.style.pointerEvents="none";let _t=G,Bn=ue,Ut=()=>{if(!Bn.textContent)return;let Qn=_t.getBoundingClientRect(),bn=de.getBoundingClientRect();Bn.style.left=`${Qn.left-bn.left}px`,Bn.style.top=`${Qn.bottom-bn.top+4}px`,Bn.style.display="block"},Dn=()=>{Bn.style.display="none"};G.addEventListener("mouseenter",Ut),G.addEventListener("mouseleave",Dn),G.appendChild(He)}let ye=y("div","persona-flex-1");xe=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 _e=y("option","");_e.value="",_e.textContent="All events (0)",xe.appendChild(_e),Be=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"),Be.type="button",Be.title="Copy All";let Ze=ge("clipboard-copy","12px","currentColor",1.5);Ze&&Be.appendChild(Ze);let Dt=y("span","persona-event-copy-all persona-text-xs");Dt.textContent="Copy All",Be.appendChild(Dt),G&&B.appendChild(G),B.appendChild(ye),B.appendChild(xe),B.appendChild(Be);let Et=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");_s(Et,L==null?void 0:L.searchBar);let yt=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),Pt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");yt&&Pt.appendChild(yt),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"),_s(K,L==null?void 0:L.searchInput),K.type="text",K.placeholder="Search event payloads...",Q=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"),Q.type="button",Q.style.display="none";let Yt=ge("x","12px","currentColor",2);return Yt&&Q.appendChild(Yt),Et.appendChild(Pt),Et.appendChild(K),Et.appendChild(Q),de.appendChild(B),de.appendChild(Et),ue&&de.appendChild(ue),de}let fe,Ke=s.find(de=>de.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&o){let de=Ke.renderEventStreamToolbar({config:o,defaultRenderer:()=>je(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{C=B,te(),vt()},onSearchChange:B=>{W=B,te(),vt()}});fe=de!=null?de:je()}else fe=je();let tt=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");tt.style.display="none";function jt(){if(!a||!He||!G)return;let de=a(),B=Ub(de);He.textContent=B;let ye=qb(de);ue&&(ue.textContent=ye,ye||(ue.style.display="none")),G.setAttribute("aria-label",ye?`Throughput: ${B}, ${ye}`:`Throughput: ${B}`)}let Qe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),he=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");he.style.height="100%";let X=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");_s(X,L==null?void 0:L.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let pt=ge(l,"14px","currentColor",2);pt&&X.appendChild(pt);let ze=y("span","");ze.textContent=p,X.appendChild(ze);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",Qe.appendChild(he),Qe.appendChild(Se),Qe.appendChild(X),k.setAttribute("tabindex","0"),k.appendChild(fe),k.appendChild(tt),k.appendChild(Qe);function ke(){let de=t.getAll(),B={};for(let Et of de)B[Et.type]=(B[Et.type]||0)+1;let ye=Object.keys(B).sort(),_e=ye.length!==U.length||!ye.every((Et,yt)=>Et===U[yt]),wt=!_e&&ye.some(Et=>B[Et]!==H[Et]),Ze=de.length!==Object.values(H).reduce((Et,yt)=>Et+yt,0);if(!_e&&!wt&&!Ze||(U=ye,H=B,!xe))return;let Dt=xe.value;if(xe.options[0].textContent=`All events (${de.length})`,_e){for(;xe.options.length>1;)xe.remove(1);for(let Et of ye){let yt=y("option","");yt.value=Et,yt.textContent=`${Et} (${B[Et]||0})`,xe.appendChild(yt)}Dt&&ye.includes(Dt)?xe.value=Dt:Dt&&(xe.value="",C="")}else for(let Et=1;Et<xe.options.length;Et++){let yt=xe.options[Et];yt.textContent=`${yt.value} (${B[yt.value]||0})`}}function rt(){let de=t.getAll();if(C&&(de=de.filter(B=>B.type===C)),W){let B=W.toLowerCase();de=de.filter(ye=>ye.type.toLowerCase().includes(B)||ye.payload.toLowerCase().includes(B))}return de}function It(){return C!==""||W!==""}function te(){F=0,Z=0,O.resume(),X.style.display="none"}function Ue(de){oe.has(de)?oe.delete(de):oe.add(de),se=de;let B=he.scrollTop,ye=O.isFollowing();Ae=!0,O.pause(),vt(),he.scrollTop=B,ye&&O.resume(),Ae=!1}function An(){return es(he,50)}function vt(){Me=Date.now(),pe=!1,jt(),ke();let de=t.getEvictedCount();de>0?(tt.textContent=`${de.toLocaleString()} older events truncated`,tt.style.display=""):tt.style.display="none",I=rt();let B=I.length,ye=t.getSize()>0;B===0&&ye&&It()?(Se.textContent=W?`No events matching '${W}'`:"No events matching filter",Se.style.display="",he.style.display="none"):(Se.style.display="none",he.style.display=""),Be&&(Be.title=It()?`Copy Filtered (${B})`:"Copy All"),d&&!O.isFollowing()&&B>F&&(Z+=B-F,ze.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",X.style.display=""),F=B;let _e=t.getAll(),wt=_e.length>0?_e[0].timestamp:0,Ze=new Set(I.map(yt=>yt.id));for(let yt of oe)Ze.has(yt)||oe.delete(yt);let Dt=C!==ce||W!==ae,Et=Ce.size===0&&I.length>0;if(Dt||Et||I.length===0){he.innerHTML="",Ce.clear();let yt=document.createDocumentFragment();for(let Pt=0;Pt<I.length;Pt++){let Yt=rc(I[Pt],Pt,wt,u,oe,Ue,s,o);Ce.set(I[Pt].id,Yt),yt.appendChild(Yt)}he.appendChild(yt),ce=C,ae=W,se=null}else{if(se!==null){let Pt=Ce.get(se);if(Pt&&Pt.parentNode===he){let Yt=I.findIndex(_t=>_t.id===se);if(Yt>=0){let _t=rc(I[Yt],Yt,wt,u,oe,Ue,s,o);he.insertBefore(_t,Pt),Pt.remove(),Ce.set(se,_t)}}se=null}let yt=new Set(I.map(Pt=>Pt.id));for(let[Pt,Yt]of Ce)yt.has(Pt)||(Yt.remove(),Ce.delete(Pt));for(let Pt=0;Pt<I.length;Pt++){let Yt=I[Pt];if(!Ce.has(Yt.id)){let _t=rc(Yt,Pt,wt,u,oe,Ue,s,o);Ce.set(Yt.id,_t),he.appendChild(_t)}}}O.isFollowing()&&(he.scrollTop=he.scrollHeight)}function yn(){if(Date.now()-Me>=Db){ee!==null&&(cancelAnimationFrame(ee),ee=null),vt();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,vt()}))}let vr=(de,B)=>{if(!Be)return;Be.innerHTML="";let ye=ge(de,"12px","currentColor",1.5);ye&&Be.appendChild(ye);let _e=y("span","persona-text-xs");_e.textContent="Copy All",Be.appendChild(_e),setTimeout(()=>{Be.innerHTML="";let wt=ge("clipboard-copy","12px","currentColor",1.5);wt&&Be.appendChild(wt);let Ze=y("span","persona-text-xs");Ze.textContent="Copy All",Be.appendChild(Ze),Be.disabled=!1},B)},wr=async()=>{if(Be){Be.disabled=!0;try{let de;It()?de=I:n?(de=await n(),de.length===0&&(de=t.getAll())):de=t.getAll();let B=de.map(ye=>{try{return JSON.parse(ye.payload)}catch{return ye.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),vr("check",1500)}catch{vr("x",1500)}}},S=()=>{xe&&(C=xe.value,te(),vt())},ne=()=>{!K||!Q||(Q.style.display=K.value?"":"none",_&&clearTimeout(_),_=setTimeout(()=>{W=K.value,te(),vt()},150))},Ee=()=>{!K||!Q||(K.value="",W="",Q.style.display="none",_&&clearTimeout(_),te(),vt())},Ne=()=>{if(Ae)return;let de=he.scrollTop,{action:B,nextLastScrollTop:ye}=Ci({following:O.isFollowing(),currentScrollTop:de,lastScrollTop:Le,nearBottom:An(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Le=ye,B==="resume"?(O.resume(),Z=0,X.style.display="none"):B==="pause"&&(O.pause(),d&&(ze.textContent=p,X.style.display=""))},Ie=de=>{let B=Ai({following:O.isFollowing(),deltaY:de.deltaY,nearBottom:An(),resumeWhenNearBottom:!0});B==="pause"?(O.pause(),d&&(ze.textContent=p,X.style.display="")):B==="resume"&&(O.resume(),Z=0,X.style.display="none")},Oe=()=>{d&&(he.scrollTop=he.scrollHeight,O.resume(),Z=0,X.style.display="none")},Je=de=>{let B=de.target;if(!B||B.closest("button"))return;let ye=B.closest("[data-event-id]");if(!ye)return;let _e=ye.getAttribute("data-event-id");_e&&Ue(_e)},lt=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),K==null||K.focus(),K==null||K.select();return}de.key==="Escape"&&(K&&document.activeElement===K?(Ee(),K.blur(),k.focus()):r&&r())};Be&&Be.addEventListener("click",wr),xe&&xe.addEventListener("change",S),K&&K.addEventListener("input",ne),Q&&Q.addEventListener("click",Ee),he.addEventListener("scroll",Ne),he.addEventListener("wheel",Ie,{passive:!0}),he.addEventListener("click",Je),X.addEventListener("click",Oe),k.addEventListener("keydown",lt);function Rt(){_&&clearTimeout(_),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,Ce.clear(),Be&&Be.removeEventListener("click",wr),xe&&xe.removeEventListener("change",S),K&&K.removeEventListener("input",ne),Q&&Q.removeEventListener("click",Ee),he.removeEventListener("scroll",Ne),he.removeEventListener("wheel",Ie),he.removeEventListener("click",Je),X.removeEventListener("click",Oe),k.removeEventListener("keydown",lt)}return{element:k,update:yn,destroy:Rt}}}function Qg(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 l=document.createElement("div");l.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 g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Yg=(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",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Qg(e,t)});if(p)return p}return Qg(e,t)};var oc=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 oc;eo.register("PersonaArtifactCard",Yg);function Vb(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 Zg(e,t){var Be,K,Q,He;let n=(K=(Be=e.features)==null?void 0:Be.artifacts)==null?void 0:K.layout,o=((Q=n==null?void 0:n.toolbarPreset)!=null?Q:"default")==="document",s=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?Ko(e.markdown):null,i=As(e.sanitize),d=G=>{let ue=a?a(G):Br(G);return i?i(ue):ue},l=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=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var G;p(),(G=t.onDismiss)==null||G.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 g=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let v=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var G;p(),(G=t.onDismiss)==null||G.call(t)});let x="rendered",M=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"}),L=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),k=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(I&&C&&C.length>0),_=null,U,H=null,F=null;if(o&&(k||I)&&!W){if(U=k?Ea({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 G=ge("chevron-down",14,"currentColor",2);G&&U.appendChild(G)}}else o&&W?(_=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),U=k?Ea({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=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"}}),_.append(U,H)):o?U=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):U=Gt({icon:"copy",label:"Copy"});let O=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Z=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Me=()=>{var Ke,tt,jt;let G=(Ke=Ce.find(Qe=>Qe.id===ce))!=null?Ke:Ce[Ce.length-1],ue=(tt=G==null?void 0:G.id)!=null?tt:null,je=(G==null?void 0:G.artifactType)==="markdown"&&(jt=G.markdown)!=null?jt:"",fe=G?JSON.stringify({component:G.component,props:G.props},null,2):"";return{markdown:je,jsonPayload:fe,id:ue}},pe=async()=>{var Ke;let{markdown:G,jsonPayload:ue}=Me(),je=(Ke=Ce.find(tt=>tt.id===ce))!=null?Ke:Ce[Ce.length-1],fe=(je==null?void 0:je.artifactType)==="markdown"?G:je?ue:"";try{await navigator.clipboard.writeText(fe)}catch{}};if(U.addEventListener("click",async()=>{let G=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(G&&W){let{markdown:ue,jsonPayload:je,id:fe}=Me();try{await G({actionId:"primary",artifactId:fe,markdown:ue,jsonPayload:je})}catch{}return}await pe()}),H&&(C!=null&&C.length)){let G=()=>{var je;return(je=u.closest("[data-persona-root]"))!=null?je:document.body},ue=()=>{F=Lo({items:C.map(je=>({id:je.id,label:je.label})),onSelect:async je=>{let{markdown:fe,jsonPayload:Ke,id:tt}=Me(),jt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{jt?await jt({actionId:je,artifactId:tt,markdown:fe,jsonPayload:Ke}):je==="markdown"||je==="md"?await navigator.clipboard.writeText(fe):je==="json"||je==="source"?await navigator.clipboard.writeText(Ke):await navigator.clipboard.writeText(fe||Ke)}catch{}},anchor:_!=null?_:H,position:"bottom-right",portal:G()})};u.isConnected?ue():requestAnimationFrame(ue),H.addEventListener("click",je=>{je.stopPropagation(),F==null||F.toggle()})}O.addEventListener("click",async()=>{var G;try{await((G=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:G.call(n))}catch{}se()}),Z.addEventListener("click",()=>{var G;p(),(G=t.onDismiss)==null||G.call(t)});let ee=()=>{o&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),P.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",ee(),se()}),P.addEventListener("click",()=>{x="source",ee(),se()});let Ae=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?(g.replaceChildren(),M.append(E,P),_?L.append(_,O,Z):L.append(U,O,Z),g.append(M,Ae,L),ee()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Le=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"),oe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Le.style.paddingLeft=s,Le.style.paddingRight=s,oe.style.padding=s),u.appendChild(g),u.appendChild(Le),u.appendChild(oe);let Ce=[],ce=null,ae=!1,se=()=>{var fe,Ke,tt,jt;let G=o&&Ce.length<=1;Le.classList.toggle("persona-hidden",G),Le.replaceChildren();for(let Qe of Ce){let he=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");he.type="button",he.textContent=Qe.title||Qe.id.slice(0,8),Qe.id===ce&&he.classList.add("persona-bg-persona-container","persona-border-persona-border"),he.addEventListener("click",()=>t.onSelect(Qe.id)),Le.appendChild(he)}oe.replaceChildren();let ue=ce&&Ce.find(Qe=>Qe.id===ce)||Ce[Ce.length-1];if(!ue)return;if(o){let Qe=ue.artifactType==="markdown"?"MD":(fe=ue.component)!=null?fe:"Component",X=(ue.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ae.textContent=`${X} \xB7 ${Qe}`}else f.textContent="Artifacts";if(ue.artifactType==="markdown"){if(o&&x==="source"){let he=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");he.textContent=(Ke=ue.markdown)!=null?Ke:"",oe.appendChild(he);return}let Qe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Qe.innerHTML=d((tt=ue.markdown)!=null?tt:""),oe.appendChild(Qe);return}let je=ue.component?eo.get(ue.component):void 0;if(je){let he={message:{id:ue.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=je((jt=ue.props)!=null?jt:{},he);if(X){oe.appendChild(X);return}}catch{}}oe.appendChild(Vb(ue))},xe=()=>{var ue;let G=Ce.length>0;if(u.classList.toggle("persona-hidden",!G),l){let je=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ke=((ue=je==null?void 0:je.classList.contains("persona-artifact-narrow-host"))!=null?ue:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;G&&Ke&&ae?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(G){var ue,je,fe;Ce=G.artifacts,ce=(fe=(je=G.selectedId)!=null?je:(ue=G.artifacts[G.artifacts.length-1])==null?void 0:ue.id)!=null?fe:null,Ce.length>0&&(ae=!0),se(),xe()},setMobileOpen(G){ae=G,!G&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):xe()}}}function cr(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 ef(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"),!cr(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 Kb(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 _i(e,t){var d,l,p,u,g,f,v,x,M,E;if(!cr(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"),Kb(e),ef(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.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",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.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"),ef(e,t)}var tf=["panel","seamless"];function $i(e,t){var i,d,l,p,u,g;for(let f of tf)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!cr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",o=tf.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 f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function nf(e,t){var n,r,o;return!t||!cr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Gb(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 Jb(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 Xb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Qb(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function rf(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 of(e,t,n,r,o,s){let a=Gb(o,200),i=Qb(t,n,r,200);i=Math.max(a,i);let d=Jb(s);return d!==null&&(i=Math.min(i,d)),Xb(e,a,i)}var sf={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"}},sc=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,M;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=sf[a])!=null?x:sf.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),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,W;let P=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");P.htmlFor=`${t.id}-${a}-${E.name}`;let L=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=E.label,P.appendChild(L);let k=(C=E.type)!=null?C:"text",I;k==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=k),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=(W=E.placeholder)!=null?W:"",E.required&&(I.required=!0),P.appendChild(I),p.appendChild(P)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async E=>{var I,C;E.preventDefault();let P=(I=n.formEndpoint)!=null?I:"/form",L=new FormData(p),k={};L.forEach((W,_)=>{k[_]=W}),k.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let _=await W.json();g.textContent=(C=_.message)!=null?C:"Thanks! We'll be in touch soon.",_.success&&_.nextPrompt&&await r.sendMessage(String(_.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ac=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()}},Ia=new ac;var af=()=>{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 Yb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Zb=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},Ra=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Yb(e),n=Zb(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}},ic=e=>typeof e=="string"?e:e==null?"":String(e),as={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ic(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=ic(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:ic(n.text)}}},lf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Wa=e=>{let t=new Set(lf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(lf(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((l,p)=>l||(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 l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var ex=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}},tx=e=>e.map(t=>({...t,streaming:!1})),nx=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?ex(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?tx(n.messages):void 0,artifacts:n.artifacts?nx(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 $s=require("partial-json");function rx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function ox(e,t){if(!rx(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 Ui(){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,$s.parse)(n,$s.STR|$s.OBJ),s=ox(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function cf(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=Ui();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function pf(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 zi(e){let t=pf(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 Vi(e){let t=pf(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 sx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ki(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:l=sx}=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,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,f.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,f.appendChild(x),g.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let C=1;C<=5;C++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),W.title=l[C-1],W.dataset.rating=String(C),W.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
|
-
`,W.addEventListener("click",()=>{u=C,E.forEach((_,U)=>{let H=U<C;_.classList.toggle("selected",H),_.setAttribute("aria-checked",U===C-1?"true":"false")})}),E.push(W),M.appendChild(W)}g.appendChild(M);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),g.appendChild(C)}let L=document.createElement("div");L.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=i,k.addEventListener("click",()=>{n==null||n(),p.remove()});let 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){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let C=(P==null?void 0:P.value.trim())||void 0;await t(u,C),p.remove()}catch(C){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),L.appendChild(k),L.appendChild(I),g.appendChild(L),p.appendChild(g),p}function Gi(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:l="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 g=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=o,v.appendChild(M),f.appendChild(v);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 L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=l;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,P.appendChild(L),P.appendChild(k);let I=document.createElement("div");I.className="persona-feedback-numbers";let C=[];for(let F=0;F<=10;F++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${F} out of 10`),O.textContent=String(F),O.dataset.rating=String(F),F<=6?O.classList.add("persona-feedback-detractor"):F<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{g=F,C.forEach((ee,Ee)=>{ee.classList.toggle("selected",Ee===F),ee.setAttribute("aria-checked",Ee===F?"true":"false")})}),C.push(O),I.appendChild(O)}E.appendChild(P),E.appendChild(I),f.appendChild(E);let W=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),F.appendChild(W),f.appendChild(F)}let _=document.createElement("div");_.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 H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=(W==null?void 0:W.value.trim())||void 0;await t(g,F),u.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),_.appendChild(U),_.appendChild(H),f.appendChild(_),u.appendChild(f),u}var js="persona-chat-history",ax=30*1e3,ix={"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 lx(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=ix[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 Ji(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 cx(e){var t,n,r,o,s,a,i,d,l;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:(l=e.clearOnChatClear)!=null?l:!0}:null}function dx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var lc=e=>!e||typeof e!="object"?{}:{...e},uf=e=>e.map(t=>({...t,streaming:!1})),mf=(e,t,n)=>{let r=e!=null&&e.markdown?Ko(e.markdown):null,o=As(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,g;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d=Vo()!==null,l;if(e!=null&&e.postprocessMessage){let f=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});l=o?o(f):f}else if(r){let f=s.streaming?um(a):a,v=r(f);l=o&&d?o(v):v}else l=Br(a);return l}};function gf(e){var i,d,l,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=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ge(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 Xi=(e,t,n)=>{var Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,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;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=fi(t),o=Ia.getForInstance(r.plugins),{plugin:s,teardown:a}=zg();r.components&&to.registerAll(r.components);let i=af(),l=r.persistState===!1?null:(Zc=r.storageAdapter)!=null?Zc:ji(),p={},u=null,g=!1,f=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:b}=m;return b&&(g=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(l!=null&&l.load)try{let c=l.load();if(c&&typeof c.then=="function")u=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return f(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=f(m);h.metadata&&(p=lc(h.metadata)),(ed=h.messages)!=null&&ed.length&&(r={...r,initialMessages:h.messages}),(td=h.artifacts)!=null&&td.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(nd=h.selectedArtifactId)!=null?nd:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=f({messages:[],metadata:{}});(rd=c.messages)!=null&&rd.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let v=()=>p,x=c=>{var h;p=(h=c({...p}))!=null?h:{},tt()},M=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ra],E=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[as.message,as.messageAndClick],P=Wa({parsers:M,handlers:E,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});P.syncFromMetadata();let L=(sd=(od=r.launcher)==null?void 0:od.enabled)!=null?sd:!0,k=(id=(ad=r.launcher)==null?void 0:ad.autoExpand)!=null?id:!1,I=(ld=r.autoFocusInput)!=null?ld:!1,C=k,W=L,_=(dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.layout,U=!1,H=()=>ko(r),F=()=>L||H(),O=H()?!1:L?k:!0,ee=!1,Ee=null,ue=()=>{ee=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{ee&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ee=!1)},1e4)},te=mf(r,P,ue),ve=(ud=(pd=r.features)==null?void 0:pd.showReasoning)!=null?ud:!0,ke=(gd=(md=r.features)==null?void 0:md.showToolCalls)!=null?gd:!0,se=(hd=(fd=r.features)==null?void 0:fd.showEventStreamToggle)!=null?hd:!1,xe=(bd=(yd=r.features)==null?void 0:yd.scrollToBottom)!=null?bd:{},pe=(vd=(xd=r.features)==null?void 0:xd.scrollBehavior)!=null?vd:{},ae=`${(Cd=typeof r.persistState=="object"?(wd=r.persistState)==null?void 0:wd.keyPrefix:void 0)!=null?Cd:"persona-"}event-stream`,He=se?new La(ae):null,Fe=(Td=(Sd=(Ad=r.features)==null?void 0:Ad.eventStream)==null?void 0:Sd.maxEvents)!=null?Td:2e3,K=se?new ka(Fe,He):null,G=se?new Pa:null,we=null,X=!1,de=null,We=0;He==null||He.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let fe={onCopy:c=>{var m,h;i.emit("message:copy",c),j!=null&&j.isClientTokenMode()&&j.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;i.emit("message:feedback",c),j!=null&&j.isClientTokenMode()&&j.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},Ge=(Ed=r.statusIndicator)!=null?Ed:{},nt=c=>{var m,h,b,T;return c==="idle"?(m=Ge.idleText)!=null?m:An.idle:c==="connecting"?(h=Ge.connectingText)!=null?h:An.connecting:c==="connected"?(b=Ge.connectedText)!=null?b:An.connected:c==="error"?(T=Ge.errorText)!=null?T:An.error:An[c]};function Pt(c,m,h,b){if(b==="idle"&&h.idleLink){c.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=m,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=m}let Ze=Rg({config:r,showClose:F()}),{wrapper:$e,panel:J,pillRoot:Ve}=Ze.shell,ze=Ze.panelElements,{container:Ce,body:Se,messagesWrapper:rt,suggestions:_t,textarea:re,sendButton:je,sendButtonWrapper:yn,composerForm:Dt,statusText:Yt,introTitle:Or,introSubtitle:wr,closeButton:S,iconHolder:ne,headerTitle:Me,headerSubtitle:De,header:Pe,footer:Ne,actionsRow:Je,leftActions:lt,rightActions:It}=ze,xt=ze.setSendButtonMode,B=ze.micButton,Y=ze.micButtonWrapper,Te=ze.attachmentButton,ct=ze.attachmentButtonWrapper,Ye=ze.attachmentInput,Ut=ze.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),Se.classList.add("persona-relative");let bn=12,vt=()=>{var c;return(c=xe.label)!=null?c:""},wt=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},Rt=()=>xe.enabled!==!1,Ct=()=>{var c;return(c=pe.mode)!=null?c:"follow"},pn=()=>{var c;return(c=pe.anchorTopOffset)!=null?c:16},$t=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");$t.type="button",$t.style.display="none",$t.setAttribute("data-persona-scroll-to-bottom","true");let On=y("span","persona-flex persona-items-center"),Tn=y("span",""),En=y("span","");En.setAttribute("data-persona-scroll-to-bottom-count",""),En.style.display="none",$t.append(On,Tn,En),Ce.appendChild($t);let vn=y("div","persona-stream-anchor-spacer");vn.setAttribute("aria-hidden","true"),vn.setAttribute("data-persona-anchor-spacer",""),vn.style.flexShrink="0",vn.style.pointerEvents="none",vn.style.height="0px",Se.appendChild(vn);let Mn=()=>{let m=Ne.style.display==="none"?0:Ne.offsetHeight;$t.style.bottom=`${m+bn}px`};Mn();let dr=()=>{let c=!!vt();$t.setAttribute("aria-label",vt()||"Jump to latest"),$t.title=vt(),$t.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),On.innerHTML="";let m=ge(wt(),"14px","currentColor",2);m?(On.appendChild(m),On.style.display=""):On.style.display="none",Tn.textContent=vt(),Tn.style.display=c?"":"none"};dr();let At=null,Cr=null,Ar=o.find(c=>c.renderHeader);if(Ar!=null&&Ar.renderHeader){let c=Ar.renderHeader({config:r,defaultRenderer:()=>{let m=eo({config:r,showClose:F()});return ts(Ce,m,r),m.header},onClose:()=>qt(!1,"user")});if(c){let m=Ce.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Pe=c,Ze.header.element=c)}}let Fr=()=>{var m,h,b,T;if(!K)return;if(X=!0,!we&&K&&(we=Xg({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>pr(),config:r,plugins:o,getThroughput:()=>{var D;return(D=G==null?void 0:G.getMetric())!=null?D:{status:"idle"}}})),we&&(Se.style.display="none",(m=Ne.parentNode)==null||m.insertBefore(we.element,Ne),we.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${Rn.actionIconColor}`;let D=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(z=>z&&mt.classList.add(z))}let c=()=>{if(!X)return;let D=Date.now();D-We>=200&&(we==null||we.update(),We=D),de=requestAnimationFrame(c)};We=0,de=requestAnimationFrame(c),at(),i.emit("eventStream:opened",{timestamp:Date.now()})},pr=()=>{var c,m,h;if(X){if(X=!1,we&&we.element.remove(),Se.style.display="",mt){mt.style.boxShadow="";let b=(h=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&mt.classList.remove(T))}de!==null&&(cancelAnimationFrame(de),de=null),at(),i.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(se){let c=(kd=(Md=r.features)==null?void 0:Md.eventStream)==null?void 0:kd.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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=y("button",m),mt.style.width="28px",mt.style.height="28px",mt.style.color=Rn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let h=ge("activity","18px","currentColor",1.5);h&&mt.appendChild(h);let b=ze.clearChatButtonWrapper,T=ze.closeButtonWrapper,D=b||T;D&&D.parentNode===Pe?Pe.insertBefore(mt,D):Pe.appendChild(mt),mt.addEventListener("click",()=>{X?pr():Fr()})}let Io=c=>{var T,D,z,$,N;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(T=c.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:c.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=c.querySelector("[data-persona-composer-form]");le!=null&&le.parentNode?le.parentNode.insertBefore(h,le):c.insertBefore(h,c.firstChild)}if(!((D=c.querySelector("[data-persona-composer-attachment-input]"))!=null?D:c.querySelector('input[type="file"]'))){let le=y("input");le.type="file",le.setAttribute("data-persona-composer-attachment-input",""),le.accept=((z=m.allowedTypes)!=null?z:Yr).join(","),le.multiple=(($=m.maxFiles)!=null?$:4)>1,le.style.display="none",le.setAttribute("aria-label",(N=m.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(le)}},Sr=o.find(c=>c.renderComposer);if(Sr!=null&&Sr.renderComposer){let c=r.composer,m=Sr.renderComposer({config:r,defaultRenderer:()=>Ds({config:r}).footer,onSubmit:h=>{var z;if(!j||j.isStreaming())return;let b=h.trim(),T=(z=At==null?void 0:At.hasAttachments())!=null?z:!1;if(!b&&!T)return;Pc();let D;T&&(D=[],D.push(...At.getContentParts()),b&&D.push(ma(b))),j.sendMessage(b,{contentParts:D}),T&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Ld=r.voiceRecognition)==null?void 0:Ld.enabled)===!0?()=>{Cr==null||Cr()}:void 0});m&&(Ze.replaceComposer(m),Ne=Ze.composer.footer)}let Ro=c=>{let m=(...ce)=>{for(let Z of ce){let be=c.querySelector(Z);if(be)return be}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),T=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),z=c.querySelector("[data-persona-composer-status]");h&&(Dt=h),b&&(re=b),T&&(je=T),D&&(B=D,Y=D.parentElement),z&&(Yt=z);let $=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(_t=$);let N=m("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(Te=N,ct=N.parentElement),Ye=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ut=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&&(Je=le)};Io(Ne),Ro(Ne);let Wn=(Hd=(Pd=r.layout)==null?void 0:Pd.contentMaxWidth)!=null?Hd:H()?(Wd=(Rd=(Id=r.launcher)==null?void 0:Id.composerBar)==null?void 0:Rd.contentMaxWidth)!=null?Wd:"720px":void 0;if(Wn&&(rt.style.maxWidth=Wn,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%"),Wn&&Dt&&!H()&&(Dt.style.maxWidth=Wn,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Wn&&_t&&!H()&&(_t.style.maxWidth=Wn,_t.style.marginLeft="auto",_t.style.marginRight="auto"),Wn&&Ut&&!H()&&(Ut.style.maxWidth=Wn,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(Bd=r.attachments)!=null&&Bd.enabled&&Ye&&Ut){At=Zo.fromConfig(r.attachments),At.setPreviewsContainer(Ut),Ye.addEventListener("change",h=>{let b=h.target;At==null||At.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=gf(c);Ce.appendChild(m)}(()=>{var b,T;let c=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},m=D=>{switch(D){case"body-top":return Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return rt;case"footer-top":return _t;case"composer":return Dt;case"footer-bottom":return Yt;default:return null}},h=(D,z)=>{var $;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Pe.insertBefore(z,Pe.firstChild);else if(D==="header-right")Pe.appendChild(z);else{let N=Pe.querySelector(".persona-flex-col");N?($=N.parentNode)==null||$.insertBefore(z,N.nextSibling):Pe.appendChild(z)}break;case"body-top":{let N=Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(z):Se.insertBefore(z,Se.firstChild);break}case"body-bottom":Se.appendChild(z);break;case"footer-top":_t.replaceWith(z);break;case"footer-bottom":Yt.replaceWith(z);break;default:break}};for(let[D,z]of Object.entries(c))if(z)try{let $=z({config:r,defaultContent:()=>m(D)});$&&h(D,$)}catch($){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,$)}})();let ro=c=>{var z,$;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")Os.has(T)?Os.delete(T):Os.add(T),Dg(T,b);else if(D==="tool")Fs.has(T)?Fs.delete(T):Fs.add(T),Ng(T,b,r);else if(D==="approval"){let N=r.approval!==!1?r.approval:void 0,le=((z=N==null?void 0:N.detailsDisplay)!=null?z:"collapsed")==="expanded",ce=($=rs.get(T))!=null?$:le;rs.set(T,!ce),$g(T,b,r)}Lr.delete(T)};rt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),ro(c))}),rt.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),ro(c))}),rt.addEventListener("copy",c=>{let{clipboardData:m}=c;if(!m)return;let h=rt.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let T=b.toString(),D=ug(T);!D||D===T||(m.setData("text/plain",D),c.preventDefault())});let _r=new Map,oo=null,so="idle",Wo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ho=(c,m)=>{let{icon:h,label:b}=Wo[m];c.setAttribute("aria-label",b),c.title=b,c.setAttribute("aria-pressed",m==="idle"?"false":"true"),c.classList.toggle("persona-message-action-active",m!=="idle"),c.classList.toggle("persona-message-action-loading",m==="loading");let T=ge(h,14,"currentColor",2);T&&(c.innerHTML="",c.appendChild(T))},ao=()=>{rt.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var D;let h=m.closest("[data-actions-for]"),b=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;Ho(m,b&&b===oo?so:"idle")})};rt.addEventListener("click",c=>{var z;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let D=h.getAttribute("data-action");if(D==="copy"){let N=j.getMessages().find(le=>le.id===T);if(N&&fe.onCopy){let le=N.content||"";navigator.clipboard.writeText(le).then(()=>{h.classList.add("persona-message-action-success");let ce=ge("check",14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=ge("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ce)}),fe.onCopy(N)}}else if(D==="read-aloud")j.toggleReadAloud(T);else if(D==="upvote"||D==="downvote"){let N=((z=_r.get(T))!=null?z:null)===D,le=D==="upvote"?"thumbs-up":"thumbs-down";if(N){_r.delete(T),h.classList.remove("persona-message-action-active");let ce=ge(le,14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce))}else{let ce=D==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ce}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ue=ge(ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Z.innerHTML="",Z.appendChild(Ue))}_r.set(T,D),h.classList.add("persona-message-action-active");let be=ge(le,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=j.getMessages().find(et=>et.id===T);Ae&&fe.onFeedback&&fe.onFeedback({type:D,messageId:Ae.id,message:Ae})}}}),rt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-approval-action");if(!D)return;let z=D==="approve"?"approved":"denied",N=j.getMessages().find(ce=>ce.id===T);if(!(N!=null&&N.approval))return;let le=b.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"?j.resolveWebMcpApproval(T,z):j.resolveApproval(N.approval,z)});let bt=null,Fn=null,_n={artifacts:[],selectedId:null},kn=!1,St={current:null};rt.addEventListener("click",c=>{var Z,be,Oe,Ae,et;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Oe=(be=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Oe.call(be,{type:"download",artifactId:b}))===!0)return;let D=j.getArtifactById(b),z=D==null?void 0:D.markdown,$=(D==null?void 0:D.title)||"artifact";if(!z){let Ue=h.closest("[data-open-artifact]"),pt=Ue==null?void 0:Ue.closest("[data-message-id]"),ot=pt==null?void 0:pt.getAttribute("data-message-id");if(ot){let Le=j.getMessages().find(qe=>qe.id===ot);if(Le!=null&&Le.rawContent)try{let qe=JSON.parse(Le.rawContent);z=(Ae=qe==null?void 0:qe.props)==null?void 0:Ae.markdown,$=((et=qe==null?void 0:qe.props)==null?void 0:et.title)||$}catch{}}}if(!z)return;let N=new Blob([z],{type:"text/markdown"}),le=URL.createObjectURL(N),ce=document.createElement("a");ce.href=le,ce.download=`${$}.md`,ce.click(),URL.revokeObjectURL(le)}),rt.addEventListener("click",c=>{var D,z,$;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||(($=(z=(D=r.features)==null?void 0:D.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:$.call(z,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),kn=!1,j.selectArtifact(b),Hn())}),rt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let Zn=ze.composerOverlay,er=(c,m,h)=>{var $,N,le,ce;let b=m.trim();if(!b||!St.current)return;let T=($=c.getAttribute("data-tool-call-id"))!=null?$:"",D=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?b.split(", "):[b],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),vo(Zn,T);let z=St.current.getMessages().find(Z=>{var be;return((be=Z.toolCall)==null?void 0:be.id)===T});(le=z==null?void 0:z.agentMetadata)!=null&&le.awaitingLocalTool?St.current.resolveAskUserQuestion(z,(ce=h.structured)!=null?ce:b):St.current.sendMessage(b)},$n=c=>{var T;let m=St.current;if(!m)return;let h=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",b=m.getMessages().find(D=>{var z;return((z=D.toolCall)==null?void 0:z.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Ja(c,b),currentIndex:ir(c)})},io=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),$r=c=>{var T,D,z;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let m=ir(c),h=Es(c);if(m>=h-1)return;let b=(z=St.current)==null?void 0:z.getMessages().find($=>{var N;return((N=$.toolCall)==null?void 0:N.id)===c.getAttribute("data-tool-call-id")});b&&(Xa(c,b,r,m+1),$n(c))};Zn.addEventListener("click",c=>{var D,z,$,N,le,ce,Z,be,Oe,Ae,et,Ue,pt,ot;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Ie=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),vo(Zn,Ie);let Le=(z=St.current)==null?void 0:z.getMessages().find(qe=>{var Ke;return((Ke=qe.toolCall)==null?void 0:Ke.id)===Ie});($=Le==null?void 0:Le.agentMetadata)!=null&&$.awaitingLocalTool&&((N=St.current)==null||N.markAskUserQuestionResolved(Le),(le=St.current)==null||le.resolveAskUserQuestion(Le,"(dismissed)"));return}if(T==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Le=b.getAttribute("data-multi-select")==="true",qe=xo(b);if(qe&&Le){let Ke=Go(b)[ir(b)],ht=new Set(Array.isArray(Ke)?Ke:[]);ht.has(Ie)?ht.delete(Ie):ht.add(Ie),wo(b,Array.from(ht)),$n(b);return}if(qe){wo(b,Ie),$n(b),$r(b);return}if(Le){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let ht=b.querySelector('[data-ask-user-action="submit-multi"]');ht&&(ht.disabled=Cl(b).length===0);return}er(b,Ie,{source:"pick",values:[Ie]});return}if(T==="submit-multi"){let Ie=Cl(b);if(Ie.length===0)return;er(b,Ie.join(", "),{source:"multi",values:Ie});return}if(T==="open-free-text"){let Ie=b.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(T==="focus-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(T==="submit-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]'),Le=(ce=Ie==null?void 0:Ie.value)!=null?ce:"";if(!Le.trim())return;if(xo(b)){wo(b,Le.trim()),$n(b),$r(b);return}er(b,Le,{source:"free-text"});return}if(T==="next"||T==="back"){if(!St.current)return;let Ie=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Le=St.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Oe=(be=qe==null?void 0:qe.value)==null?void 0:be.trim())!=null?Oe:"";if(Ke){let Be=Go(b)[ir(b)];(typeof Be!="string"||Be!==Ke)&&wo(b,Ke)}let ht=T==="next"?1:-1,R=ir(b)+ht;Xa(b,Le,r,R),$n(b);return}if(T==="submit-all"){if(!St.current)return;let Ie=(Ae=b.getAttribute("data-tool-call-id"))!=null?Ae:"",Le=St.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ue=(et=qe==null?void 0:qe.value)==null?void 0:et.trim())!=null?Ue:"";Ke&&wo(b,Ke);let ht=Ja(b,Le);St.current.persistAskUserQuestionProgress(Le,{answers:ht,currentIndex:ir(b)});let R=io(ht);er(b,R||"(submitted)",{source:"submit-all",structured:ht});return}if(T==="skip"){if(!St.current)return;let Ie=(pt=b.getAttribute("data-tool-call-id"))!=null?pt:"",Le=St.current.getMessages().find(Re=>{var me;return((me=Re.toolCall)==null?void 0:me.id)===Ie});if(!Le)return;let qe=xo(b),Ke=ir(b),ht=Es(b),R=Ke>=ht-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),vo(Zn,Ie),(ot=Le.agentMetadata)!=null&&ot.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Le),St.current.resolveAskUserQuestion(Le,"(dismissed)"));return}wo(b,"");let Be=b.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),R){let Re=Ja(b,Le),me=io(Re);er(b,me||"(skipped)",{source:"submit-all",structured:Re});return}Xa(b,Le,r,Ke+1),$n(b);return}}),Zn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let h=c.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let T=h.value;if(T.trim()){if(xo(b)){wo(b,T.trim()),$n(b),$r(b);return}er(b,T,{source:"free-text"})}});let lo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Zn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",lo);let jn=null,Wt=null,Ln=null,tr=null,co=()=>{};function jr(){tr==null||tr(),tr=null}let po=()=>{var z;if(!jn||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=jn.firstElementChild;if(!b||b===Wt)return;let T=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${T}px`,Wt.style.zIndex="5";let D=b.offsetWidth-T/2;Wt.style.left=`${Math.max(0,D)}px`},ye=()=>{},Hn=()=>{var h,b,T,D,z;if(!bt||!cr(r))return;_i(e,r),$i(e,r),ye();let c=(D=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),bt.update(_n),kn?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(z=bt.backdrop)==null||z.classList.add("persona-hidden")):_n.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),co()};if(cr(r)){J.style.position="relative";let c=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");c.appendChild(Ce),bt=Zg(r,{onSelect:h=>{var b;return(b=St.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{kn=!0,Hn()}}),bt.element.classList.add("persona-hidden"),jn=m,m.appendChild(c),m.appendChild(bt.element),bt.backdrop&&J.appendChild(bt.backdrop),J.appendChild(m),co=()=>{var b,T,D,z;if(!jn||!bt)return;if(!(((D=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){Ln==null||Ln(),Ln=null,jr(),Wt&&(Wt.remove(),Wt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Wt){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=(z=N.defaultView)!=null?z:window,ce=Z=>{var pt,ot;if(!bt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||le.innerWidth<=640)return;Z.preventDefault(),jr();let be=Z.clientX,Oe=bt.element.getBoundingClientRect().width,Ae=(ot=(pt=r.features)==null?void 0:pt.artifacts)==null?void 0:ot.layout,et=Ie=>{let Le=jn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Ke=qe?0:rf(jn,le),ht=qe?0:$.getBoundingClientRect().width||6,R=Oe-(Ie.clientX-be),Be=of(R,Le,Ke,ht,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);bt.element.style.width=`${Be}px`,bt.element.style.maxWidth="none",po()},Ue=()=>{N.removeEventListener("pointermove",et),N.removeEventListener("pointerup",Ue),N.removeEventListener("pointercancel",Ue),tr=null;try{$.releasePointerCapture(Z.pointerId)}catch{}};tr=Ue,N.addEventListener("pointermove",et),N.addEventListener("pointerup",Ue),N.addEventListener("pointercancel",Ue);try{$.setPointerCapture(Z.pointerId)}catch{}};$.addEventListener("pointerdown",ce),Wt=$,jn.insertBefore($,bt.element),Ln=()=>{$.removeEventListener("pointerdown",ce)}}if(Wt){let $=_n.artifacts.length>0&&!kn;Wt.classList.toggle("persona-hidden",!$),po()}},ye=()=>{var le,ce,Z,be,Oe,Ae,et,Ue,pt,ot,Ie,Le,qe,Ke;if(!L||!bt||((ce=(le=r.launcher)==null?void 0:le.sidebarMode)!=null?ce:!1)||on(r)&&Qn(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,T=(Oe=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Oe:!0,D=(et=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?et:640;if(T&&b.innerWidth<=D||!nf(r,L))return;let z=(ot=(pt=(Ue=r.launcher)==null?void 0:Ue.width)!=null?pt:r.launcherWidth)!=null?ot:Xn,$=(Ke=(qe=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!kn?(J.style.width=$,J.style.maxWidth=$):(J.style.width=z,J.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Hn()}),Fn.observe(J))}else J.appendChild(Ce),H()&&Ve&&(ze.peekBanner&&Ve.appendChild(ze.peekBanner),Ve.appendChild(Ne));e.appendChild($e),Ve&&e.appendChild(Ve);let Tr=()=>{var Be,Re,me,Nt,Ht,Jt,yt,zt,Vn,tn,Xe,Mt,rn,sr,Kn,_o,$o,xs,vs,Xt,jo,go,fo,Gr,Uo,fr,Wr,Qe;if(H()){J.style.width="100%",J.style.maxWidth="100%";let Ot=(Re=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Re:{},Kt=$e.dataset.state==="expanded",Ft=(me=Ot.expandedSize)!=null?me:"anchored";if(!(Kt&&Ft!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let kt=(Ht=(Nt=r.theme)==null?void 0:Nt.components)==null?void 0:Ht.panel,jt=Hs(r),gn=(hn,ar)=>{var ho;return hn==null||hn===""?ar:(ho=Rs(jt,hn))!=null?ho:hn},Gn="1px solid var(--persona-border)",Hr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",fn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=gn(kt==null?void 0:kt.border,Gn),Ce.style.borderRadius=gn(kt==null?void 0:kt.borderRadius,fn),Ce.style.boxShadow=gn(kt==null?void 0:kt.shadow,Hr),Ce.style.overflow="hidden";return}let c=on(r),m=(yt=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?yt:!1,h=c||m||((Vn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Vn:!1),b=((tn=r.launcher)==null?void 0:tn.enabled)===!1,T=(Mt=(Xe=r.theme)==null?void 0:Xe.components)==null?void 0:Mt.panel,D=Hs(r),z=(Ot,Kt)=>{var Ft;return Ot==null||Ot===""?Kt:(Ft=Rs(D,Ot))!=null?Ft:Ot},$=(rn=e.ownerDocument.defaultView)!=null?rn:window,N=(Kn=(sr=r.launcher)==null?void 0:sr.mobileFullscreen)!=null?Kn:!0,le=($o=(_o=r.launcher)==null?void 0:_o.mobileBreakpoint)!=null?$o:640,ce=$.innerWidth<=le,Z=N&&ce&&L,be=(vs=(xs=r.launcher)==null?void 0:xs.position)!=null?vs:"bottom-left",Oe=be==="bottom-left"||be==="top-left",Ae=(jo=(Xt=r.launcher)==null?void 0:Xt.zIndex)!=null?jo:Sn,et=m||Z?"none":"1px solid var(--persona-border)",Ue=Z?"none":m?Oe?"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))";c&&!Z&&(Ue="none",et="none");let pt=m||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ot=z(T==null?void 0:T.border,et),Ie=z(T==null?void 0:T.shadow,Ue),Le=z(T==null?void 0:T.borderRadius,pt),qe=Se.scrollTop;e.style.cssText="",$e.style.cssText="",J.style.cssText="",Ce.style.cssText="",Se.style.cssText="",Ne.style.cssText="";let Ke=()=>{var Kt;if(qe<=0)return;((Kt=Se.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(Se.scrollTop===qe)return;let Ft=Se.scrollHeight-Se.clientHeight;Ft<=0||(Se.scrollTop=Math.min(qe,Ft))})};if(Z){$e.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),$e.style.cssText=`
|
|
34
|
+
`,W.addEventListener("click",()=>{u=C,E.forEach((_,U)=>{let H=U<C;_.classList.toggle("selected",H),_.setAttribute("aria-checked",U===C-1?"true":"false")})}),E.push(W),M.appendChild(W)}g.appendChild(M);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),g.appendChild(C)}let L=document.createElement("div");L.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=i,k.addEventListener("click",()=>{n==null||n(),p.remove()});let 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){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let C=(P==null?void 0:P.value.trim())||void 0;await t(u,C),p.remove()}catch(C){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),L.appendChild(k),L.appendChild(I),g.appendChild(L),p.appendChild(g),p}function Gi(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:l="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 g=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=o,v.appendChild(M),f.appendChild(v);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 L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=l;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,P.appendChild(L),P.appendChild(k);let I=document.createElement("div");I.className="persona-feedback-numbers";let C=[];for(let F=0;F<=10;F++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${F} out of 10`),O.textContent=String(F),O.dataset.rating=String(F),F<=6?O.classList.add("persona-feedback-detractor"):F<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{g=F,C.forEach((Z,Me)=>{Z.classList.toggle("selected",Me===F),Z.setAttribute("aria-checked",Me===F?"true":"false")})}),C.push(O),I.appendChild(O)}E.appendChild(P),E.appendChild(I),f.appendChild(E);let W=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),F.appendChild(W),f.appendChild(F)}let _=document.createElement("div");_.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 H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=(W==null?void 0:W.value.trim())||void 0;await t(g,F),u.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),_.appendChild(U),_.appendChild(H),f.appendChild(_),u.appendChild(f),u}var js="persona-chat-history",ax=30*1e3,ix={"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 lx(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=ix[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 Ji(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 cx(e){var t,n,r,o,s,a,i,d,l;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:(l=e.clearOnChatClear)!=null?l:!0}:null}function dx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var lc=e=>!e||typeof e!="object"?{}:{...e},uf=e=>e.map(t=>({...t,streaming:!1})),mf=(e,t,n)=>{let r=e!=null&&e.markdown?Ko(e.markdown):null,o=As(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,g;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d=Vo()!==null,l;if(e!=null&&e.postprocessMessage){let f=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});l=o?o(f):f}else if(r){let f=s.streaming?um(a):a,v=r(f);l=o&&d?o(v):v}else l=Br(a);return l}};function gf(e){var i,d,l,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=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ge(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 Xi=(e,t,n)=>{var Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,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;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=fi(t),o=Ia.getForInstance(r.plugins),{plugin:s,teardown:a}=zg();r.components&&eo.registerAll(r.components);let i=af(),l=r.persistState===!1?null:(Zc=r.storageAdapter)!=null?Zc:ji(),p={},u=null,g=!1,f=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:b}=m;return b&&(g=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(l!=null&&l.load)try{let c=l.load();if(c&&typeof c.then=="function")u=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return f(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=f(m);h.metadata&&(p=lc(h.metadata)),(ed=h.messages)!=null&&ed.length&&(r={...r,initialMessages:h.messages}),(td=h.artifacts)!=null&&td.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(nd=h.selectedArtifactId)!=null?nd:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=f({messages:[],metadata:{}});(rd=c.messages)!=null&&rd.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let v=()=>p,x=c=>{var h;p=(h=c({...p}))!=null?h:{},nt()},M=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ra],E=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[as.message,as.messageAndClick],P=Wa({parsers:M,handlers:E,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});P.syncFromMetadata();let L=(sd=(od=r.launcher)==null?void 0:od.enabled)!=null?sd:!0,k=(id=(ad=r.launcher)==null?void 0:ad.autoExpand)!=null?id:!1,I=(ld=r.autoFocusInput)!=null?ld:!1,C=k,W=L,_=(dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.layout,U=!1,H=()=>ko(r),F=()=>L||H(),O=H()?!1:L?k:!0,Z=!1,Me=null,pe=()=>{Z=!0,Me&&clearTimeout(Me),Me=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=mf(r,P,pe),Ae=(ud=(pd=r.features)==null?void 0:pd.showReasoning)!=null?ud:!0,Le=(gd=(md=r.features)==null?void 0:md.showToolCalls)!=null?gd:!0,oe=(hd=(fd=r.features)==null?void 0:fd.showEventStreamToggle)!=null?hd:!1,Ce=(bd=(yd=r.features)==null?void 0:yd.scrollToBottom)!=null?bd:{},ce=(vd=(xd=r.features)==null?void 0:xd.scrollBehavior)!=null?vd:{},se=`${(Cd=typeof r.persistState=="object"?(wd=r.persistState)==null?void 0:wd.keyPrefix:void 0)!=null?Cd:"persona-"}event-stream`,xe=oe?new La(se):null,Be=(Td=(Sd=(Ad=r.features)==null?void 0:Ad.eventStream)==null?void 0:Sd.maxEvents)!=null?Td:2e3,K=oe?new ka(Be,xe):null,Q=oe?new Pa:null,He=null,G=!1,ue=null,je=0;xe==null||xe.open().then(()=>K==null?void 0:K.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let fe={onCopy:c=>{var m,h;i.emit("message:copy",c),j!=null&&j.isClientTokenMode()&&j.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;i.emit("message:feedback",c),j!=null&&j.isClientTokenMode()&&j.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},Ke=(Ed=r.statusIndicator)!=null?Ed:{},tt=c=>{var m,h,b,T;return c==="idle"?(m=Ke.idleText)!=null?m:wn.idle:c==="connecting"?(h=Ke.connectingText)!=null?h:wn.connecting:c==="connected"?(b=Ke.connectedText)!=null?b:wn.connected:c==="error"?(T=Ke.errorText)!=null?T:wn.error:wn[c]};function jt(c,m,h,b){if(b==="idle"&&h.idleLink){c.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=m,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=m}let Qe=Rg({config:r,showClose:F()}),{wrapper:he,panel:X,pillRoot:pt}=Qe.shell,ze=Qe.panelElements,{container:Se,body:ke,messagesWrapper:rt,suggestions:It,textarea:te,sendButton:Ue,sendButtonWrapper:An,composerForm:vt,statusText:yn,introTitle:vr,introSubtitle:wr,closeButton:S,iconHolder:ne,headerTitle:Ee,headerSubtitle:Ne,header:Ie,footer:Oe,actionsRow:Je,leftActions:lt,rightActions:Rt}=ze,de=ze.setSendButtonMode,B=ze.micButton,ye=ze.micButtonWrapper,_e=ze.attachmentButton,wt=ze.attachmentButtonWrapper,Ze=ze.attachmentInput,Dt=ze.attachmentPreviewsContainer;Se.classList.add("persona-relative"),ke.classList.add("persona-relative");let Et=12,yt=()=>{var c;return(c=Ce.label)!=null?c:""},Pt=()=>{var c;return(c=Ce.iconName)!=null?c:"arrow-down"},Yt=()=>Ce.enabled!==!1,_t=()=>{var c;return(c=ce.mode)!=null?c:"follow"},Bn=()=>{var c;return(c=ce.anchorTopOffset)!=null?c:16},Ut=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");Ut.type="button",Ut.style.display="none",Ut.setAttribute("data-persona-scroll-to-bottom","true");let Dn=y("span","persona-flex persona-items-center"),Qn=y("span",""),bn=y("span","");bn.setAttribute("data-persona-scroll-to-bottom-count",""),bn.style.display="none",Ut.append(Dn,Qn,bn),Se.appendChild(Ut);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",ke.appendChild(Ln);let Yn=()=>{let m=Oe.style.display==="none"?0:Oe.offsetHeight;Ut.style.bottom=`${m+Et}px`};Yn();let no=()=>{let c=!!yt();Ut.setAttribute("aria-label",yt()||"Jump to latest"),Ut.title=yt(),Ut.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Dn.innerHTML="";let m=ge(Pt(),"14px","currentColor",2);m?(Dn.appendChild(m),Dn.style.display=""):Dn.style.display="none",Qn.textContent=yt(),Qn.style.display=c?"":"none"};no();let Ct=null,Cr=null,Ar=o.find(c=>c.renderHeader);if(Ar!=null&&Ar.renderHeader){let c=Ar.renderHeader({config:r,defaultRenderer:()=>{let m=Zr({config:r,showClose:F()});return ts(Se,m,r),m.header},onClose:()=>qt(!1,"user")});if(c){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Ie=c,Qe.header.element=c)}}let Or=()=>{var m,h,b,T;if(!K)return;if(G=!0,!He&&K&&(He=Xg({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>dr(),config:r,plugins:o,getThroughput:()=>{var D;return(D=Q==null?void 0:Q.getMetric())!=null?D:{status:"idle"}}})),He&&(ke.style.display="none",(m=Oe.parentNode)==null||m.insertBefore(He.element,Oe),He.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${kn.actionIconColor}`;let D=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(z=>z&&mt.classList.add(z))}let c=()=>{if(!G)return;let D=Date.now();D-je>=200&&(He==null||He.update(),je=D),ue=requestAnimationFrame(c)};je=0,ue=requestAnimationFrame(c),at(),i.emit("eventStream:opened",{timestamp:Date.now()})},dr=()=>{var c,m,h;if(G){if(G=!1,He&&He.element.remove(),ke.style.display="",mt){mt.style.boxShadow="";let b=(h=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&mt.classList.remove(T))}ue!==null&&(cancelAnimationFrame(ue),ue=null),at(),i.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(oe){let c=(kd=(Md=r.features)==null?void 0:Md.eventStream)==null?void 0:kd.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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=y("button",m),mt.style.width="28px",mt.style.height="28px",mt.style.color=kn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let h=ge("activity","18px","currentColor",1.5);h&&mt.appendChild(h);let b=ze.clearChatButtonWrapper,T=ze.closeButtonWrapper,D=b||T;D&&D.parentNode===Ie?Ie.insertBefore(mt,D):Ie.appendChild(mt),mt.addEventListener("click",()=>{G?dr():Or()})}let Io=c=>{var T,D,z,$,N;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(T=c.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:c.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 ie=c.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):c.insertBefore(h,c.firstChild)}if(!((D=c.querySelector("[data-persona-composer-attachment-input]"))!=null?D:c.querySelector('input[type="file"]'))){let ie=y("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=((z=m.allowedTypes)!=null?z:Qr).join(","),ie.multiple=(($=m.maxFiles)!=null?$:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(N=m.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(ie)}},Sr=o.find(c=>c.renderComposer);if(Sr!=null&&Sr.renderComposer){let c=r.composer,m=Sr.renderComposer({config:r,defaultRenderer:()=>Ds({config:r}).footer,onSubmit:h=>{var z;if(!j||j.isStreaming())return;let b=h.trim(),T=(z=Ct==null?void 0:Ct.hasAttachments())!=null?z:!1;if(!b&&!T)return;Pc();let D;T&&(D=[],D.push(...Ct.getContentParts()),b&&D.push(ma(b))),j.sendMessage(b,{contentParts:D}),T&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ze==null||Ze.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Ld=r.voiceRecognition)==null?void 0:Ld.enabled)===!0?()=>{Cr==null||Cr()}:void 0});m&&(Qe.replaceComposer(m),Oe=Qe.composer.footer)}let Ro=c=>{let m=(...le)=>{for(let Y of le){let we=c.querySelector(Y);if(we)return we}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),T=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),z=c.querySelector("[data-persona-composer-status]");h&&(vt=h),b&&(te=b),T&&(Ue=T),D&&(B=D,ye=D.parentElement),z&&(yn=z);let $=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(It=$);let N=m("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(_e=N,wt=N.parentElement),Ze=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Dt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(Je=ie)};Io(Oe),Ro(Oe);let Pn=(Hd=(Pd=r.layout)==null?void 0:Pd.contentMaxWidth)!=null?Hd:H()?(Wd=(Rd=(Id=r.launcher)==null?void 0:Id.composerBar)==null?void 0:Rd.contentMaxWidth)!=null?Wd:"720px":void 0;if(Pn&&(rt.style.maxWidth=Pn,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%"),Pn&&vt&&!H()&&(vt.style.maxWidth=Pn,vt.style.marginLeft="auto",vt.style.marginRight="auto"),Pn&&It&&!H()&&(It.style.maxWidth=Pn,It.style.marginLeft="auto",It.style.marginRight="auto"),Pn&&Dt&&!H()&&(Dt.style.maxWidth=Pn,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),(Bd=r.attachments)!=null&&Bd.enabled&&Ze&&Dt){Ct=Zo.fromConfig(r.attachments),Ct.setPreviewsContainer(Dt),Ze.addEventListener("change",h=>{let b=h.target;Ct==null||Ct.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=gf(c);Se.appendChild(m)}(()=>{var b,T;let c=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},m=D=>{switch(D){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return rt;case"footer-top":return It;case"composer":return vt;case"footer-bottom":return yn;default:return null}},h=(D,z)=>{var $;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Ie.insertBefore(z,Ie.firstChild);else if(D==="header-right")Ie.appendChild(z);else{let N=Ie.querySelector(".persona-flex-col");N?($=N.parentNode)==null||$.insertBefore(z,N.nextSibling):Ie.appendChild(z)}break;case"body-top":{let N=ke.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(z):ke.insertBefore(z,ke.firstChild);break}case"body-bottom":ke.appendChild(z);break;case"footer-top":It.replaceWith(z);break;case"footer-bottom":yn.replaceWith(z);break;default:break}};for(let[D,z]of Object.entries(c))if(z)try{let $=z({config:r,defaultContent:()=>m(D)});$&&h(D,$)}catch($){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,$)}})();let ro=c=>{var z,$;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")Os.has(T)?Os.delete(T):Os.add(T),Dg(T,b);else if(D==="tool")Fs.has(T)?Fs.delete(T):Fs.add(T),Ng(T,b,r);else if(D==="approval"){let N=r.approval!==!1?r.approval:void 0,ie=((z=N==null?void 0:N.detailsDisplay)!=null?z:"collapsed")==="expanded",le=($=rs.get(T))!=null?$:ie;rs.set(T,!le),$g(T,b,r)}Lr.delete(T)};rt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),ro(c))}),rt.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),ro(c))}),rt.addEventListener("copy",c=>{let{clipboardData:m}=c;if(!m)return;let h=rt.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let T=b.toString(),D=ug(T);!D||D===T||(m.setData("text/plain",D),c.preventDefault())});let Fr=new Map,oo=null,so="idle",Wo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ho=(c,m)=>{let{icon:h,label:b}=Wo[m];c.setAttribute("aria-label",b),c.title=b,c.setAttribute("aria-pressed",m==="idle"?"false":"true"),c.classList.toggle("persona-message-action-active",m!=="idle"),c.classList.toggle("persona-message-action-loading",m==="loading");let T=ge(h,14,"currentColor",2);T&&(c.innerHTML="",c.appendChild(T))},ao=()=>{rt.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var D;let h=m.closest("[data-actions-for]"),b=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;Ho(m,b&&b===oo?so:"idle")})};rt.addEventListener("click",c=>{var z;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let D=h.getAttribute("data-action");if(D==="copy"){let N=j.getMessages().find(ie=>ie.id===T);if(N&&fe.onCopy){let ie=N.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let le=ge("check",14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=ge("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),fe.onCopy(N)}}else if(D==="read-aloud")j.toggleReadAloud(T);else if(D==="upvote"||D==="downvote"){let N=((z=Fr.get(T))!=null?z:null)===D,ie=D==="upvote"?"thumbs-up":"thumbs-down";if(N){Fr.delete(T),h.classList.remove("persona-message-action-active");let le=ge(ie,14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le))}else{let le=D==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${le}"]`);if(Y){Y.classList.remove("persona-message-action-active");let qe=ge(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Y.innerHTML="",Y.appendChild(qe))}Fr.set(T,D),h.classList.add("persona-message-action-active");let we=ge(ie,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Te=j.getMessages().find(et=>et.id===T);Te&&fe.onFeedback&&fe.onFeedback({type:D,messageId:Te.id,message:Te})}}}),rt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-approval-action");if(!D)return;let z=D==="approve"?"approved":"denied",N=j.getMessages().find(le=>le.id===T);if(!(N!=null&&N.approval))return;let ie=b.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?j.resolveWebMcpApproval(T,z):j.resolveApproval(N.approval,z)});let xt=null,Nn=null,On={artifacts:[],selectedId:null},Sn=!1,At={current:null};rt.addEventListener("click",c=>{var Y,we,Fe,Te,et;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(we=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let D=j.getArtifactById(b),z=D==null?void 0:D.markdown,$=(D==null?void 0:D.title)||"artifact";if(!z){let qe=h.closest("[data-open-artifact]"),dt=qe==null?void 0:qe.closest("[data-message-id]"),ot=dt==null?void 0:dt.getAttribute("data-message-id");if(ot){let Pe=j.getMessages().find(Ve=>Ve.id===ot);if(Pe!=null&&Pe.rawContent)try{let Ve=JSON.parse(Pe.rawContent);z=(Te=Ve==null?void 0:Ve.props)==null?void 0:Te.markdown,$=((et=Ve==null?void 0:Ve.props)==null?void 0:et.title)||$}catch{}}}if(!z)return;let N=new Blob([z],{type:"text/markdown"}),ie=URL.createObjectURL(N),le=document.createElement("a");le.href=ie,le.download=`${$}.md`,le.click(),URL.revokeObjectURL(ie)}),rt.addEventListener("click",c=>{var D,z,$;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||(($=(z=(D=r.features)==null?void 0:D.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:$.call(z,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),Sn=!1,j.selectArtifact(b),In())}),rt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let Zn=ze.composerOverlay,er=(c,m,h)=>{var $,N,ie,le;let b=m.trim();if(!b||!At.current)return;let T=($=c.getAttribute("data-tool-call-id"))!=null?$:"",D=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?b.split(", "):[b],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),vo(Zn,T);let z=At.current.getMessages().find(Y=>{var we;return((we=Y.toolCall)==null?void 0:we.id)===T});(ie=z==null?void 0:z.agentMetadata)!=null&&ie.awaitingLocalTool?At.current.resolveAskUserQuestion(z,(le=h.structured)!=null?le:b):At.current.sendMessage(b)},Fn=c=>{var T;let m=At.current;if(!m)return;let h=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",b=m.getMessages().find(D=>{var z;return((z=D.toolCall)==null?void 0:z.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Ja(c,b),currentIndex:ir(c)})},io=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),_r=c=>{var T,D,z;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let m=ir(c),h=Es(c);if(m>=h-1)return;let b=(z=At.current)==null?void 0:z.getMessages().find($=>{var N;return((N=$.toolCall)==null?void 0:N.id)===c.getAttribute("data-tool-call-id")});b&&(Xa(c,b,r,m+1),Fn(c))};Zn.addEventListener("click",c=>{var D,z,$,N,ie,le,Y,we,Fe,Te,et,qe,dt,ot;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Re=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),vo(Zn,Re);let Pe=(z=At.current)==null?void 0:z.getMessages().find(Ve=>{var Ge;return((Ge=Ve.toolCall)==null?void 0:Ge.id)===Re});($=Pe==null?void 0:Pe.agentMetadata)!=null&&$.awaitingLocalTool&&((N=At.current)==null||N.markAskUserQuestionResolved(Pe),(ie=At.current)==null||ie.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(T==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Pe=b.getAttribute("data-multi-select")==="true",Ve=xo(b);if(Ve&&Pe){let Ge=Go(b)[ir(b)],ht=new Set(Array.isArray(Ge)?Ge:[]);ht.has(Re)?ht.delete(Re):ht.add(Re),wo(b,Array.from(ht)),Fn(b);return}if(Ve){wo(b,Re),Fn(b),_r(b);return}if(Pe){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let ht=b.querySelector('[data-ask-user-action="submit-multi"]');ht&&(ht.disabled=Cl(b).length===0);return}er(b,Re,{source:"pick",values:[Re]});return}if(T==="submit-multi"){let Re=Cl(b);if(Re.length===0)return;er(b,Re.join(", "),{source:"multi",values:Re});return}if(T==="open-free-text"){let Re=b.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Pe=Re.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(T==="focus-free-text"){let Re=b.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(T==="submit-free-text"){let Re=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(le=Re==null?void 0:Re.value)!=null?le:"";if(!Pe.trim())return;if(xo(b)){wo(b,Pe.trim()),Fn(b),_r(b);return}er(b,Pe,{source:"free-text"});return}if(T==="next"||T==="back"){if(!At.current)return;let Re=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",Pe=At.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Re});if(!Pe)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),Ge=(Fe=(we=Ve==null?void 0:Ve.value)==null?void 0:we.trim())!=null?Fe:"";if(Ge){let De=Go(b)[ir(b)];(typeof De!="string"||De!==Ge)&&wo(b,Ge)}let ht=T==="next"?1:-1,R=ir(b)+ht;Xa(b,Pe,r,R),Fn(b);return}if(T==="submit-all"){if(!At.current)return;let Re=(Te=b.getAttribute("data-tool-call-id"))!=null?Te:"",Pe=At.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Re});if(!Pe)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),Ge=(qe=(et=Ve==null?void 0:Ve.value)==null?void 0:et.trim())!=null?qe:"";Ge&&wo(b,Ge);let ht=Ja(b,Pe);At.current.persistAskUserQuestionProgress(Pe,{answers:ht,currentIndex:ir(b)});let R=io(ht);er(b,R||"(submitted)",{source:"submit-all",structured:ht});return}if(T==="skip"){if(!At.current)return;let Re=(dt=b.getAttribute("data-tool-call-id"))!=null?dt:"",Pe=At.current.getMessages().find(We=>{var me;return((me=We.toolCall)==null?void 0:me.id)===Re});if(!Pe)return;let Ve=xo(b),Ge=ir(b),ht=Es(b),R=Ge>=ht-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),vo(Zn,Re),(ot=Pe.agentMetadata)!=null&&ot.awaitingLocalTool&&(At.current.markAskUserQuestionResolved(Pe),At.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}wo(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),R){let We=Ja(b,Pe),me=io(We);er(b,me||"(skipped)",{source:"submit-all",structured:We});return}Xa(b,Pe,r,Ge+1),Fn(b);return}}),Zn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let h=c.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let T=h.value;if(T.trim()){if(xo(b)){wo(b,T.trim()),Fn(b),_r(b);return}er(b,T,{source:"free-text"})}});let lo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Zn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",lo);let _n=null,Wt=null,Tn=null,tr=null,co=()=>{};function $r(){tr==null||tr(),tr=null}let po=()=>{var z;if(!_n||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=_n.firstElementChild;if(!b||b===Wt)return;let T=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${T}px`,Wt.style.zIndex="5";let D=b.offsetWidth-T/2;Wt.style.left=`${Math.max(0,D)}px`},ve=()=>{},In=()=>{var h,b,T,D,z;if(!xt||!cr(r))return;_i(e,r),$i(e,r),ve();let c=(D=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),xt.update(On),Sn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(z=xt.backdrop)==null||z.classList.add("persona-hidden")):On.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),co()};if(cr(r)){X.style.position="relative";let c=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");c.appendChild(Se),xt=Zg(r,{onSelect:h=>{var b;return(b=At.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Sn=!0,In()}}),xt.element.classList.add("persona-hidden"),_n=m,m.appendChild(c),m.appendChild(xt.element),xt.backdrop&&X.appendChild(xt.backdrop),X.appendChild(m),co=()=>{var b,T,D,z;if(!_n||!xt)return;if(!(((D=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){Tn==null||Tn(),Tn=null,$r(),Wt&&(Wt.remove(),Wt=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!Wt){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,ie=(z=N.defaultView)!=null?z:window,le=Y=>{var dt,ot;if(!xt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;Y.preventDefault(),$r();let we=Y.clientX,Fe=xt.element.getBoundingClientRect().width,Te=(ot=(dt=r.features)==null?void 0:dt.artifacts)==null?void 0:ot.layout,et=Re=>{let Pe=_n.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ve?0:rf(_n,ie),ht=Ve?0:$.getBoundingClientRect().width||6,R=Fe-(Re.clientX-we),De=of(R,Pe,Ge,ht,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);xt.element.style.width=`${De}px`,xt.element.style.maxWidth="none",po()},qe=()=>{N.removeEventListener("pointermove",et),N.removeEventListener("pointerup",qe),N.removeEventListener("pointercancel",qe),tr=null;try{$.releasePointerCapture(Y.pointerId)}catch{}};tr=qe,N.addEventListener("pointermove",et),N.addEventListener("pointerup",qe),N.addEventListener("pointercancel",qe);try{$.setPointerCapture(Y.pointerId)}catch{}};$.addEventListener("pointerdown",le),Wt=$,_n.insertBefore($,xt.element),Tn=()=>{$.removeEventListener("pointerdown",le)}}if(Wt){let $=On.artifacts.length>0&&!Sn;Wt.classList.toggle("persona-hidden",!$),po()}},ve=()=>{var ie,le,Y,we,Fe,Te,et,qe,dt,ot,Re,Pe,Ve,Ge;if(!L||!xt||((le=(ie=r.launcher)==null?void 0:ie.sidebarMode)!=null?le:!1)||on(r)&&Jn(r).reveal==="emerge")return;let b=(Y=e.ownerDocument.defaultView)!=null?Y:window,T=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,D=(et=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?et:640;if(T&&b.innerWidth<=D||!nf(r,L))return;let z=(ot=(dt=(qe=r.launcher)==null?void 0:qe.width)!=null?dt:r.launcherWidth)!=null?ot:Gn,$=(Ge=(Ve=(Pe=(Re=r.features)==null?void 0:Re.artifacts)==null?void 0:Pe.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Sn?(X.style.width=$,X.style.maxWidth=$):(X.style.width=z,X.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{In()}),Nn.observe(X))}else X.appendChild(Se),H()&&pt&&(ze.peekBanner&&pt.appendChild(ze.peekBanner),pt.appendChild(Oe));e.appendChild(he),pt&&e.appendChild(pt);let Tr=()=>{var De,We,me,Nt,Ht,Jt,bt,zt,qn,tn,Xe,Mt,rn,sr,zn,_o,$o,xs,vs,Xt,jo,go,fo,Kr,Uo,gr,Wr,Ye;if(H()){X.style.width="100%",X.style.maxWidth="100%";let Ot=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Kt=he.dataset.state==="expanded",Ft=(me=Ot.expandedSize)!=null?me:"anchored";if(!(Kt&&Ft!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let kt=(Ht=(Nt=r.theme)==null?void 0:Nt.components)==null?void 0:Ht.panel,$t=Hs(r),mn=(fn,ar)=>{var ho;return fn==null||fn===""?ar:(ho=Rs($t,fn))!=null?ho:fn},Vn="1px solid var(--persona-border)",Hr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",gn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=mn(kt==null?void 0:kt.border,Vn),Se.style.borderRadius=mn(kt==null?void 0:kt.borderRadius,gn),Se.style.boxShadow=mn(kt==null?void 0:kt.shadow,Hr),Se.style.overflow="hidden";return}let c=on(r),m=(bt=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?bt:!1,h=c||m||((qn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?qn:!1),b=((tn=r.launcher)==null?void 0:tn.enabled)===!1,T=(Mt=(Xe=r.theme)==null?void 0:Xe.components)==null?void 0:Mt.panel,D=Hs(r),z=(Ot,Kt)=>{var Ft;return Ot==null||Ot===""?Kt:(Ft=Rs(D,Ot))!=null?Ft:Ot},$=(rn=e.ownerDocument.defaultView)!=null?rn:window,N=(zn=(sr=r.launcher)==null?void 0:sr.mobileFullscreen)!=null?zn:!0,ie=($o=(_o=r.launcher)==null?void 0:_o.mobileBreakpoint)!=null?$o:640,le=$.innerWidth<=ie,Y=N&&le&&L,we=(vs=(xs=r.launcher)==null?void 0:xs.position)!=null?vs:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Te=(jo=(Xt=r.launcher)==null?void 0:Xt.zIndex)!=null?jo:Cn,et=m||Y?"none":"1px solid var(--persona-border)",qe=Y?"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))";c&&!Y&&(qe="none",et="none");let dt=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ot=z(T==null?void 0:T.border,et),Re=z(T==null?void 0:T.shadow,qe),Pe=z(T==null?void 0:T.borderRadius,dt),Ve=ke.scrollTop;e.style.cssText="",he.style.cssText="",X.style.cssText="",Se.style.cssText="",ke.style.cssText="",Oe.style.cssText="",G&&(ke.style.display="none");let Ge=()=>{var Kt;if(Ve<=0)return;((Kt=ke.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(ke.scrollTop===Ve)return;let Ft=ke.scrollHeight-ke.clientHeight;Ft<=0||(ke.scrollTop=Math.min(Ve,Ft))})};if(Y){he.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"),he.style.cssText=`
|
|
35
35
|
position: fixed !important;
|
|
36
36
|
inset: 0 !important;
|
|
37
37
|
width: 100% !important;
|
|
@@ -41,9 +41,9 @@ _Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
41
41
|
padding: 0 !important;
|
|
42
42
|
display: flex !important;
|
|
43
43
|
flex-direction: column !important;
|
|
44
|
-
z-index: ${
|
|
44
|
+
z-index: ${Te} !important;
|
|
45
45
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
46
|
-
`,
|
|
46
|
+
`,X.style.cssText=`
|
|
47
47
|
position: relative !important;
|
|
48
48
|
display: flex !important;
|
|
49
49
|
flex-direction: column !important;
|
|
@@ -56,7 +56,7 @@ _Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
56
56
|
padding: 0 !important;
|
|
57
57
|
box-shadow: none !important;
|
|
58
58
|
border-radius: 0 !important;
|
|
59
|
-
`,
|
|
59
|
+
`,Se.style.cssText=`
|
|
60
60
|
display: flex !important;
|
|
61
61
|
flex-direction: column !important;
|
|
62
62
|
flex: 1 1 0% !important;
|
|
@@ -67,7 +67,7 @@ _Details: ${n.message}_`:r}var ha=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
|
-
`,
|
|
70
|
+
`,ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",Oe.style.flexShrink="0",U=!0,Ge();return}let ht=(fo=(go=r==null?void 0:r.launcher)==null?void 0:go.width)!=null?fo:r==null?void 0:r.launcherWidth,R=ht!=null?ht:Gn;if(!m&&!c)b&&h?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=R,X.style.maxWidth=R);else if(c)if(Jn(r).reveal==="emerge"){let Kt=Jn(r).width;X.style.width=Kt,X.style.maxWidth=Kt}else X.style.width="100%",X.style.maxWidth="100%";if(ve(),X.style.boxShadow=Re,X.style.borderRadius=Pe,Se.style.border=ot,Se.style.borderRadius=Pe,c&&!Y&&(T==null?void 0:T.border)===void 0&&(Se.style.border="none",Jn(r).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",b&&(he.style.overflow="hidden"),X.style.display="flex",X.style.flexDirection="column",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.maxHeight="100%",X.style.height="100%",X.style.overflow="hidden",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.overflow="hidden",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",Oe.style.flexShrink="0"),he.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&&!b&&!c&&((Kr=xr[we])!=null?Kr:xr["bottom-right"]).split(" ").forEach(Kt=>he.classList.add(Kt)),m){let Ot=(gr=(Uo=r.launcher)==null?void 0:Uo.sidebarWidth)!=null?gr:"420px";he.style.cssText=`
|
|
71
71
|
position: fixed !important;
|
|
72
72
|
top: 0 !important;
|
|
73
73
|
bottom: 0 !important;
|
|
@@ -78,9 +78,9 @@ _Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
78
78
|
padding: 0 !important;
|
|
79
79
|
display: flex !important;
|
|
80
80
|
flex-direction: column !important;
|
|
81
|
-
z-index: ${
|
|
82
|
-
${
|
|
83
|
-
`,
|
|
81
|
+
z-index: ${Te} !important;
|
|
82
|
+
${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
83
|
+
`,X.style.cssText=`
|
|
84
84
|
position: relative !important;
|
|
85
85
|
display: flex !important;
|
|
86
86
|
flex-direction: column !important;
|
|
@@ -91,9 +91,9 @@ _Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
91
91
|
min-height: 0 !important;
|
|
92
92
|
margin: 0 !important;
|
|
93
93
|
padding: 0 !important;
|
|
94
|
-
box-shadow: ${
|
|
95
|
-
border-radius: ${
|
|
96
|
-
`,
|
|
94
|
+
box-shadow: ${Re} !important;
|
|
95
|
+
border-radius: ${Pe} !important;
|
|
96
|
+
`,X.style.setProperty("width","100%","important"),X.style.setProperty("max-width","100%","important"),Se.style.cssText=`
|
|
97
97
|
display: flex !important;
|
|
98
98
|
flex-direction: column !important;
|
|
99
99
|
flex: 1 1 0% !important;
|
|
@@ -102,13 +102,13 @@ _Details: ${n.message}_`:r}var ha=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
102
102
|
min-height: 0 !important;
|
|
103
103
|
max-height: 100% !important;
|
|
104
104
|
overflow: hidden !important;
|
|
105
|
-
border-radius: ${
|
|
105
|
+
border-radius: ${Pe} !important;
|
|
106
106
|
border: ${ot} !important;
|
|
107
|
-
`,
|
|
107
|
+
`,Oe.style.cssText=`
|
|
108
108
|
flex-shrink: 0 !important;
|
|
109
109
|
border-top: none !important;
|
|
110
110
|
padding: 8px 16px 12px 16px !important;
|
|
111
|
-
`}if(!b&&!c){let Ot="max-height: -moz-available !important; max-height: stretch !important;",Kt=m?"":"padding-top: 1.25em !important;",Ft=m?"":`z-index: ${(Qe=(Wr=r.launcher)==null?void 0:Wr.zIndex)!=null?Qe:Sn} !important;`;$e.style.cssText+=Ot+Kt+Ft}Ke()};Tr(),To(e,r),_i(e,r),$i(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",lo)});let sn=null,an=null;gt.push(()=>{sn==null||sn(),sn=null,an==null||an(),an=null}),Fn&>.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),gt.push(()=>{Ln==null||Ln(),Ln=null,jr(),Wt&&(Wt.remove(),Wt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),se&>.push(()=>{de!==null&&(cancelAnimationFrame(de),de=null),we==null||we.destroy(),we=null,K==null||K.destroy(),K=null,He=null});let Er=null,Us=()=>{Er&&(Er(),Er=null),r.colorScheme==="auto"&&(Er=bi(()=>{To(e,r)}))};Us(),gt.push(()=>{Er&&(Er(),Er=null)}),gt.push(a);let Ur=(Dd=r.features)==null?void 0:Dd.streamAnimation;if(Ur!=null&&Ur.type&&Ur.type!=="none"){let c=wa(Ur.type,Ur.plugins);c&&(_l(c,e),gt.push(()=>Mg(e)))}let Bo=Vg(_t),Mr=null,j,ls=c=>{var b,T;if(!j)return;let m=c!=null?c:j.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?Ya(m):null;h?Bo.render(h,j,re,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?Bo.render([],j,re,m):Bo.render(r.suggestionChips,j,re,m,r.suggestionChipsConfig)},kr=!1,Lr=fg(),qr=new Map,Pr=new Map,ur=new Map,cs=0,Da=Vo()!==null,Un=wi(),qn=0,mr=null,gr=!1,Do=!1,zr=0,wn=null,Ir=null,ds=!1,No=!1,ps=null,Na=4,us=24,Oa=80,ms=new Map,ut={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},qs=(Od=(Nd=r.voiceRecognition)==null?void 0:Nd.autoResume)!=null?Od:!1,nr=c=>{i.emit("voice:state",{active:ut.active,source:c,timestamp:Date.now()})},Bn=()=>{x(c=>({...c,voiceState:{active:ut.active,timestamp:Date.now(),manuallyDeactivated:ut.manuallyDeactivated}}))},Fa=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=lc(p.voiceState),m=!!c.active,h=Number((T=c.timestamp)!=null?T:0);ut.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<ax&&setTimeout(()=>{var D,z;ut.active||(ut.manuallyDeactivated=!1,((z=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:z.type)==="runtype"?j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),nr("restore"),j.isVoiceActive()&&ys()}):$a("restore"))},1e3)},gs=()=>j?uf(j.getMessages()).filter(c=>!c.__skipPersist):[];function tt(c){if(!(l!=null&&l.save))return;let h={messages:c?uf(c):j?gs():[],metadata:p,artifacts:_n.artifacts,selectedArtifactId:_n.selectedId};try{let b=l.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let w=null,V=()=>$e.querySelector("#persona-scroll-container")||Se,q=()=>{w!==null&&(cancelAnimationFrame(w),w=null),gr=!1},Q=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),Do=!1,q()},he=()=>{zr>0?(En.textContent=String(zr),En.style.display="",$t.setAttribute("aria-label",`${vt()||"Jump to latest"} (${zr} new)`)):(En.textContent="",En.style.display="none",$t.setAttribute("aria-label",vt()||"Jump to latest"))},_e=()=>{zr!==0&&(zr=0,he())},ft=()=>Ct()==="follow"?!Un.isFollowing():!es(Se,us),at=()=>{if(!Rt()||X){$t.parentNode&&$t.remove(),$t.style.display="none";return}$t.parentNode!==Ce&&Ce.appendChild($t),Mn();let m=Zr(Se)>0&&ft();m||_e(),$t.style.display=m?"":"none"},zs=()=>{Un.pause()&&(Q(),at())},Dn=()=>{Un.resume(),_e(),at()},un=(c=!1)=>{Ct()==="follow"&&Un.isFollowing()&&(!c&&!kr||(mr!==null&&(cancelAnimationFrame(mr),mr=null),Do=!0,mr=requestAnimationFrame(()=>{mr=null,Do=!1,Un.isFollowing()&&Oo(V(),c?220:140)})))},mn=(c,m,h,b=()=>!0)=>{let T=c.scrollTop,D=m(),z=D-T;q();let $=performance.now();gr=!0;let N=ce=>1-Math.pow(1-ce,3),le=ce=>{if(!b()){q();return}let Z=m();Z!==D&&(D=Z,z=D-T);let be=ce-$,Oe=Math.min(be/h,1),Ae=N(Oe),et=T+z*Ae;c.scrollTop=et,qn=c.scrollTop,Oe<1?w=requestAnimationFrame(le):(c.scrollTop=D,qn=c.scrollTop,w=null,gr=!1)};w=requestAnimationFrame(le)},Oo=(c,m=500)=>{let h=Zr(c)-c.scrollTop;if(Math.abs(h)<1){qn=c.scrollTop;return}if(Math.abs(h)>=Oa){q(),gr=!0,c.scrollTop=Zr(c),qn=c.scrollTop,gr=!1;return}mn(c,()=>Zr(c),m,()=>Un.isFollowing())},Vr=()=>{let c=V();gr=!0,c.scrollTop=Zr(c),qn=c.scrollTop,gr=!1,at()},Pn=c=>{vn.style.height=`${Math.max(0,Math.round(c))}px`,wn&&(wn.spacerHeight=Math.max(0,c))},xn=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),q(),wn=null,vn.style.height="0px"},zn=c=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var le;Ir=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=Se.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Se;)b+=T.offsetTop,T=T.offsetParent;let D=(le=wn==null?void 0:wn.spacerHeight)!=null?le:0,z=Se.scrollHeight-D,{targetScrollTop:$,spacerHeight:N}=vg({anchorOffsetTop:b,topOffset:pn(),viewportHeight:Se.clientHeight,contentHeight:z});wn={initialSpacerHeight:N,contentHeightAtAnchor:z,spacerHeight:N},Pn(N),mn(Se,()=>$,220)})},Zf=()=>{if(Ct()==="follow"){if(!Un.isFollowing()||es(Se,1))return;un(!kr);return}if(wn&&wn.initialSpacerHeight>0){let c=Se.scrollHeight-wn.spacerHeight,m=wg({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:c});m!==wn.spacerHeight&&Pn(m)}at()},eh=c=>{let m=Ct();m==="follow"?(Dn(),un(!0)):m==="anchor-top"&&zn(c)},th=c=>{let m=new Map;c.forEach(h=>{let b=ms.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!No&&Ct()!=="anchor-top"&&ft()&&(zr+=1,he(),at())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),ms.clear(),m.forEach((h,b)=>{ms.set(b,h)})},nh=(c,m,h)=>{var ot,Ie,Le,qe,Ke,ht;let b=document.createElement("div"),D=(()=>{var Be;let R=o.find(Re=>Re.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),z=(R,Be)=>Be==null?!1:typeof Be=="string"?(R.textContent=Be,!0):(R.appendChild(Be),!0),$=new Set,N=new Set,le=o.some(R=>R.renderAskUserQuestion),ce=[],Z=[],be=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Ae=[];if(m.forEach(R=>{var Xe,Mt,rn,sr,Kn,_o,$o,xs,vs,Xt,jo,go,fo,Gr,Uo,fr,Wr;$.add(R.id);let Be=le&&Jr(R),Re=Oe&&R.variant==="approval"&&!!R.approval,me=!Be&&R.role==="assistant"&&!R.variant&&be&&zi(R);if(!Re&&ur.has(R.id)){let Qe=c.querySelector(`#wrapper-${R.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),ur.delete(R.id)}if(!me&&Pr.has(R.id)){let Qe=c.querySelector(`#wrapper-${R.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Pr.delete(R.id)}let Nt=Jr(R)?`:${(Xe=R.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Mt=R.agentMetadata)!=null&&Mt.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ht=gg(R,cs)+Nt,Jt=Be||Re||me?null:hg(Lr,R.id,Ht);if(Jt){b.appendChild(Jt.cloneNode(!0)),Jr(R)&&((rn=R.toolCall)!=null&&rn.id)&&((sr=R.agentMetadata)==null?void 0:sr.awaitingLocalTool)===!0&&!((Kn=R.agentMetadata)!=null&&Kn.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ms(R,r,ze.composerOverlay));return}let yt=null,zt=o.find(Qe=>!!(R.variant==="reasoning"&&Qe.renderReasoning||R.variant==="tool"&&Qe.renderToolCall||!R.variant&&Qe.renderMessage)),Vn=(_o=r.layout)==null?void 0:_o.messages;if(Jr(R)&&(($o=R.agentMetadata)==null?void 0:$o.askUserQuestionAnswered)===!0){qr.delete(R.id);let Qe=c.querySelector(`#wrapper-${R.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(la(R)&&((vs=(xs=r.features)==null?void 0:xs.suggestReplies)==null?void 0:vs.enabled)!==!1)return;if(Jr(R)&&((jo=(Xt=r.features)==null?void 0:Xt.askUserQuestion)==null?void 0:jo.enabled)!==!1){let Qe=o.find(Ot=>typeof Ot.renderAskUserQuestion=="function");if(Qe&&St.current){let Ot=qr.get(R.id),Kt=Ot!==Ht,Ft=null;if(Kt){let{payload:jt,complete:gn}=Xr(R),Gn=R.id,Hr=()=>{var fn;return(fn=St.current)==null?void 0:fn.getMessages().find(hn=>hn.id===Gn)};Ft=Qe.renderAskUserQuestion({message:R,payload:jt,complete:gn,resolve:fn=>{var ar;let hn=Hr();hn&&((ar=St.current)==null||ar.resolveAskUserQuestion(hn,fn))},dismiss:()=>{var hn,ar,ho;let fn=Hr();(hn=fn==null?void 0:fn.agentMetadata)!=null&&hn.awaitingLocalTool&&((ar=St.current)==null||ar.markAskUserQuestionResolved(fn),(ho=St.current)==null||ho.resolveAskUserQuestion(fn,"(dismissed)"))},config:r})}let Qt=Ot!=null;if(Kt&&Ft===null&&!Qt){((go=R.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=R.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ms(R,r,ze.composerOverlay));return}let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${R.id}`,kt.setAttribute("data-wrapper-id",R.id),kt.setAttribute("data-ask-plugin-stub","true"),kt.setAttribute("data-preserve-runtime","true"),b.appendChild(kt),ce.push({messageId:R.id,fingerprint:Ht,bubble:Ft});return}else{((Gr=R.agentMetadata)==null?void 0:Gr.awaitingLocalTool)===!0&&!((Uo=R.agentMetadata)!=null&&Uo.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ms(R,r,ze.composerOverlay));return}}else if(Re){let Qe=(fr=o.find(Qt=>typeof Qt.renderApproval=="function"))!=null?fr:s,Kt=ur.get(R.id)!==Ht,Ft=null;if(Kt&&(Qe!=null&&Qe.renderApproval)){let Qt=R.id,kt=(jt,gn)=>{var Hr,fn,hn;let Gn=(Hr=St.current)==null?void 0:Hr.getMessages().find(ar=>ar.id===Qt);Gn!=null&&Gn.approval&&(Gn.approval.toolType==="webmcp"?(fn=St.current)==null||fn.resolveWebMcpApproval(Gn.id,jt):(hn=St.current)==null||hn.resolveApproval(Gn.approval,jt,gn))};Ft=Qe.renderApproval({message:R,defaultRenderer:()=>Oi(R,r),config:r,approve:jt=>kt("approved",jt),deny:jt=>kt("denied",jt)})}if(Kt&&Ft===null){let Qt=c.querySelector(`#wrapper-${R.id}`);Qt==null||Qt.removeAttribute("data-preserve-runtime"),ur.delete(R.id),yt=Oi(R,r)}else{let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${R.id}`,Qt.setAttribute("data-wrapper-id",R.id),Qt.setAttribute("data-approval-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),b.appendChild(Qt),Ae.push({messageId:R.id,fingerprint:Ht,bubble:Ft});return}}else if(zt)if(R.variant==="reasoning"&&R.reasoning&&zt.renderReasoning){if(!ve)return;yt=zt.renderReasoning({message:R,defaultRenderer:()=>Yl(R,r),config:r})}else if(R.variant==="tool"&&R.toolCall&&zt.renderToolCall){if(!ke)return;yt=zt.renderToolCall({message:R,defaultRenderer:()=>ec(R,r),config:r})}else zt.renderMessage&&(yt=zt.renderMessage({message:R,defaultRenderer:()=>{let Qe=Ns(R,h,Vn,r.messageActions,fe,{loadingIndicatorRenderer:D,widgetConfig:r});return R.role!=="user"&&sc(Qe,R,r,j),Qe},config:r}));if(!yt&&me){let Qe=Vi(R);if(Qe){let Ot=Pr.get(R.id),Kt=Ot!==Ht,Ft=r.wrapComponentDirectiveInBubble!==!1,Qt=null;if(Kt){let kt=qi(Qe,{config:r,message:R,transform:h});if(kt)if(Ft){let jt=document.createElement("div");if(jt.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(" "),jt.id=`bubble-${R.id}`,jt.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),jt.appendChild(gn)}jt.appendChild(kt),Qt=jt}else{let jt=document.createElement("div");if(jt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",jt.id=`bubble-${R.id}`,jt.setAttribute("data-message-id",R.id),jt.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),jt.appendChild(gn)}jt.appendChild(kt),Qt=jt}}if(Qt||Ot!=null){let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${R.id}`,kt.setAttribute("data-wrapper-id",R.id),kt.setAttribute("data-component-directive-stub","true"),kt.setAttribute("data-preserve-runtime","true"),Ft||kt.classList.add("persona-w-full"),b.appendChild(kt),Z.push({messageId:R.id,fingerprint:Ht,bubble:Qt});return}}}if(!yt)if(R.variant==="reasoning"&&R.reasoning){if(!ve)return;yt=Yl(R,r)}else if(R.variant==="tool"&&R.toolCall){if(!ke)return;yt=ec(R,r)}else if(R.variant==="approval"&&R.approval){if(r.approval===!1)return;yt=Oi(R,r)}else{let Qe=(Wr=r.layout)==null?void 0:Wr.messages;Qe!=null&&Qe.renderUserMessage&&R.role==="user"?yt=Qe.renderUserMessage({message:R,config:r,streaming:!!R.streaming}):Qe!=null&&Qe.renderAssistantMessage&&R.role==="assistant"?yt=Qe.renderAssistantMessage({message:R,config:r,streaming:!!R.streaming}):yt=Ns(R,h,Qe,r.messageActions,fe,{loadingIndicatorRenderer:D,widgetConfig:r}),R.role!=="user"&&yt&&sc(yt,R,r,j)}let tn=document.createElement("div");tn.className="persona-flex",tn.id=`wrapper-${R.id}`,tn.setAttribute("data-wrapper-id",R.id),R.role==="user"&&tn.classList.add("persona-justify-end"),(yt==null?void 0:yt.getAttribute("data-persona-component-directive"))==="true"&&tn.classList.add("persona-w-full"),tn.appendChild(yt),yg(Lr,R.id,Ht,tn),b.appendChild(tn)}),ze.composerOverlay&&ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Re=Be.getAttribute("data-persona-ask-sheet-for");Re&&!N.has(Re)&&vo(ze.composerOverlay,Re)}),(Ie=(ot=r.features)==null?void 0:ot.toolCallDisplay)!=null&&Ie.grouped){let R=[],Be=[];m.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&ke){Be.push(Re);return}Be.length>1&&R.push(Be),Be=[]}),Be.length>1&&R.push(Be),R.forEach((Re,me)=>{var Xe,Mt;let Nt=Re.map(rn=>Array.from(b.children).find(sr=>sr instanceof HTMLElement&&sr.getAttribute("data-wrapper-id")===rn.id)).filter(rn=>!!rn);if(Nt.length<2)return;let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-tool-group-${me}-${Re[0].id}`,Ht.setAttribute("data-wrapper-id",`tool-group-${me}-${Re[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Re.length} tools`,Vn=(Mt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Mt.call(Xe,{messages:Re,toolCalls:Re.map(rn=>rn.toolCall).filter(rn=>!!rn),defaultSummary:zt,config:r});z(yt,Vn)||(yt.textContent=zt);let tn=document.createElement("div");tn.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(yt,tn),Ht.appendChild(Jt),Nt[0].before(Ht),Nt.forEach((rn,sr)=>{let Kn=document.createElement("div");Kn.className="persona-tool-group-item persona-relative",Kn.setAttribute("data-persona-tool-group-item","true"),sr<Nt.length-1&&Kn.setAttribute("data-persona-tool-group-connector","true"),Kn.appendChild(rn),tn.appendChild(Kn)})})}bg(Lr,$);let et=m.some(R=>R.role==="assistant"&&R.streaming),Ue=m[m.length-1],pt=(Ue==null?void 0:Ue.role)==="assistant"&&!Ue.streaming&&Ue.variant!=="approval";if(kr&&m.some(R=>R.role==="user")&&!et&&!pt){let R={config:r,streaming:!0,location:"standalone",defaultRenderer:ns},Be=o.find(me=>me.renderLoadingIndicator),Re=null;if(Be!=null&&Be.renderLoadingIndicator&&(Re=Be.renderLoadingIndicator(R)),Re===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Re=r.loadingIndicator.render(R)),Re===null&&(Re=ns()),Re){let me=document.createElement("div"),Nt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;me.className=Nt?["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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(Re);let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id="wrapper-typing-indicator",Ht.setAttribute("data-wrapper-id","typing-indicator"),Ht.appendChild(me),b.appendChild(Ht)}}if(!kr&&m.length>0){let R=m[m.length-1],Be={config:r,lastMessage:R,messageCount:m.length},Re=o.find(Nt=>Nt.renderIdleIndicator),me=null;if(Re!=null&&Re.renderIdleIndicator&&(me=Re.renderIdleIndicator(Be)),me===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(me=r.loadingIndicator.renderIdle(Be)),me){let Nt=document.createElement("div"),Ht=((ht=r.loadingIndicator)==null?void 0:ht.showBubble)!==!1;Nt.className=Ht?["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(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(me);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(Nt),b.appendChild(Jt)}}if(xi(c,b),ce.length>0)for(let{messageId:R,fingerprint:Be,bubble:Re}of ce){let me=c.querySelector(`#wrapper-${R}`);me&&Re!==null&&(me.replaceChildren(Re),me.setAttribute("data-bubble-fp",Be),qr.set(R,Be))}if(qr.size>0)for(let R of qr.keys())$.has(R)||qr.delete(R);if(Z.length>0)for(let{messageId:R,fingerprint:Be,bubble:Re}of Z){let me=c.querySelector(`#wrapper-${R}`);me&&Re!==null&&(me.replaceChildren(Re),me.setAttribute("data-bubble-fp",Be),Pr.set(R,Be))}if(Pr.size>0)for(let R of Pr.keys())$.has(R)||Pr.delete(R);if(Ae.length>0)for(let{messageId:R,fingerprint:Be,bubble:Re}of Ae){let me=c.querySelector(`#wrapper-${R}`);me&&Re!==null&&(me.replaceChildren(Re),me.setAttribute("data-bubble-fp",Be),ur.set(R,Be))}if(ur.size>0)for(let R of ur.keys())$.has(R)||ur.delete(R)},Vs=(c,m,h)=>{nh(c,m,h),ao()},Ks=null,rh=()=>{var h;if(Ks)return;let c=b=>{let T=b.composedPath();T.includes($e)||Ve&&T.includes(Ve)||qt(!1,"user")};Ks=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Ec=()=>{var m;if(!Ks)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Ks,!0),Ks=null};gt.push(()=>Ec());let Gs=null,oh=()=>{var h;if(Gs)return;let c=b=>{b.key==="Escape"&&(b.isComposing||qt(!1,"user"))};Gs=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Mc=()=>{var m;if(!Gs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Gs,!0),Gs=null};gt.push(()=>Mc());let Js=!1,kc=new Set,sh=()=>{var m,h,b,T;let c=(b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},fs=()=>{var pt,ot,Ie,Le;if(!H())return;let c=ze.peekBanner,m=ze.peekTextNode;if(!c||!m)return;if(O){c.classList.remove("persona-pill-peek--visible");return}let h=(pt=j==null?void 0:j.getMessages())!=null?pt:[],b;for(let qe=h.length-1;qe>=0;qe--){let Ke=h[qe];if(Ke.role==="assistant"&&Ke.content){b=Ke;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let T=b.content,D=!!b.streaming,z=sh(),$=Si(z),N=$.type!=="none"?wa($.type,z==null?void 0:z.plugins):null,le=((ot=N==null?void 0:N.isAnimating)==null?void 0:ot.call(N,b))===!0,ce=N!==null&&(D||le);ce&&N&&!kc.has(N.name)&&(_l(N,e),kc.add(N.name));let Z=ce&&(N!=null&&N.containerClass)?N.containerClass:null,be=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;be&&be!==Z&&(m.classList.remove(be),delete m.dataset.personaPeekStreamClass),Z&&be!==Z&&(m.classList.add(Z),m.dataset.personaPeekStreamClass=Z),ce?(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 Oe=ce?Ti(T,$.buffer,N,b,D):T;if(ce&&$.placeholder==="skeleton"&&D&&(!Oe||!Oe.trim())){let qe=document.createElement("div"),Ke=Aa();Ke.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ke),xi(m,qe)}else{let qe=Math.max(0,Oe.length-100),Ke=Oe.length>100?Oe.slice(-100):Oe,ht=Br(Ke);if(!ce||!N){let R=Oe.length>100?`\u2026${Ke}`:Ke;m.textContent!==R&&(m.textContent=R)}else{let R=ht;(N.wrap==="char"||N.wrap==="word")&&(R=Ca(ht,N.wrap,`peek-${b.id}`,{skipTags:N.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=R,N.useCaret&&Ke.length>0){let Re=Ei(),me=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=me[me.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(Re,Nt.nextSibling):Be.appendChild(Re)}xi(m,Be),(Le=N.onAfterRender)==null||Le.call(N,{container:m,bubble:c,messageId:b.id,message:b,speed:$.speed,duration:$.duration})}}let Ue=kr||Js;c.classList.toggle("persona-pill-peek--visible",Ue)};if(H()){let c=ze.peekBanner;if(c){let b=T=>{T.preventDefault(),T.stopPropagation(),qt(!0,"user")};c.addEventListener("pointerdown",b),gt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Js||(Js=!0,fs())},h=()=>{Js&&(Js=!1,fs())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",h),gt.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",h)}),Ve&&(Ve.addEventListener("pointerenter",m),Ve.addEventListener("pointerleave",h),gt.push(()=>{Ve.removeEventListener("pointerenter",m),Ve.removeEventListener("pointerleave",h)}))}let ah=c=>{var be,Oe,Ae,et,Ue,pt,ot,Ie;let m=(Oe=(be=r.launcher)==null?void 0:be.composerBar)!=null?Oe:{},h=(Ae=m.expandedSize)!=null?Ae:"anchored",b=(et=m.bottomOffset)!=null?et:"16px",T=m.collapsedMaxWidth,D=(Ue=m.expandedMaxWidth)!=null?Ue:"880px",z=(pt=m.expandedTopOffset)!=null?pt:"5vh",$=(ot=m.modalMaxWidth)!=null?ot:"880px",N=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",le="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",Z=$e.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ve){let Le=Ve.style;Le.bottom=b,Le.width=T!=null?T:""}if(c&&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(${b} + ${ce})`,Z.top=z,Z.width=D,Z.maxWidth=le}},Xs=()=>{var N,le,ce,Z,be,Oe,Ae,et;if(!F())return;if(H()){let pt=(ce=((le=(N=r.launcher)==null?void 0:N.composerBar)!=null?le:{}).expandedSize)!=null?ce:"anchored",ot=O?"expanded":"collapsed";$e.dataset.state=ot,$e.dataset.expandedSize=pt,Ve&&(Ve.dataset.state=ot,Ve.dataset.expandedSize=pt),$e.style.removeProperty("display"),$e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ah(O),Ce.style.display=O?"flex":"none",Tr(),O?(rh(),oh()):(Ec(),Mc()),fs();return}let c=on(r),m=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Oe=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Oe:640,b=(et=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?et:!0,T=m.innerWidth<=h,D=b&&T&&L,z=Qn(r).reveal;O?($e.style.removeProperty("display"),$e.style.display=c?"flex":"",$e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0"),J.classList.add("persona-scale-100","persona-opacity-100"),en?en.element.style.display="none":ln&&(ln.style.display="none")):(c?c&&(z==="overlay"||z==="push")&&!D?($e.style.removeProperty("display"),$e.style.display="flex",$e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):($e.style.setProperty("display","none","important"),$e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):($e.style.display="",$e.classList.add("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100"),J.classList.add("persona-scale-95","persona-opacity-0")),en?en.element.style.display=c?"none":"":ln&&(ln.style.display=c?"none":""))},qt=(c,m="user")=>{var D,z;if(!F()||O===c)return;let h=O;O=c,Xs();let b=(()=>{var Ae,et,Ue,pt,ot,Ie,Le,qe,Ke,ht;let $=(et=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?et:!1,N=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,le=(ot=(pt=r.launcher)==null?void 0:pt.mobileFullscreen)!=null?ot:!0,ce=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,Z=N.innerWidth<=ce,be=on(r)&&le&&Z,Oe=H()&&((ht=(Ke=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ke.expandedSize)!=null?ht:"fullscreen")==="fullscreen";return $||le&&Z&&L||be||Oe})();if(O&&b){if(!sn){let $=e.getRootNode(),N=$ instanceof ShadowRoot?$.host:e.closest(".persona-host");N&&(sn=$l(N,(z=(D=r.launcher)==null?void 0:D.zIndex)!=null?z:Sn))}an||(an=jl(e.ownerDocument))}else O||(sn==null||sn(),sn=null,an==null||an(),an=null);O&&(Qs(),Ct()==="follow"?un(!0):Vr());let T={open:O,source:m,timestamp:Date.now()};O&&!h?i.emit("widget:opened",T):!O&&h&&i.emit("widget:closed",T),i.emit("widget:state",{open:O,launcherEnabled:L,voiceActive:ut.active,streaming:j.isStreaming()})},ol=c=>{xt(c?"stop":"send"),B&&(B.disabled=c),Bo.buttons.forEach(m=>{m.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},sl=()=>{ut.active||re&&re.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>sl(),200)});let Lc=()=>{var h,b,T,D,z,$,N,le,ce,Z,be;Or.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",wr.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",re.placeholder=($=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?$:"How can I help...";let c=Se.querySelector("[data-persona-intro-card]");if(c){let Oe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;c.style.display=Oe?"":"none",Oe?(Se.classList.remove("persona-gap-3"),Se.classList.add("persona-gap-6")):(Se.classList.remove("persona-gap-6"),Se.classList.add("persona-gap-3"))}!((ce=(le=r.sendButton)==null?void 0:le.useIcon)!=null&&ce)&&!(j!=null&&j.isStreaming())&&(je.textContent=(be=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?be:"Send"),re.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',re.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=p.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{x(m=>({...m,sessionId:c}))}});let Fo=null,ih=()=>{Fo==null&&(Fo=setInterval(()=>{let c=rt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Fo),Fo=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=ei(m-b))})},100))};j=new Is(r,{onMessagesChanged(c){var b;Vs(rt,c,te),ih(),ls(c),un(!kr),th(c);let m=[...c].reverse().find(T=>T.role==="user");c.length===0&&xn(),!ds||No?(ds=!0,ps=(b=m==null?void 0:m.id)!=null?b:null):m&&m.id!==ps&&(ps=m.id,eh(m.id));let h=ut.lastUserMessageId;m&&m.id!==h&&(ut.lastUserMessageId=m.id,i.emit("user:message",m)),ut.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),tt(c),fs()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Pt(Yt,(T=>{var D,z,$,N;return T==="idle"?(D=m.idleText)!=null?D:An.idle:T==="connecting"?(z=m.connectingText)!=null?z:An.connecting:T==="connected"?($=m.connectedText)!=null?$:An.connected:T==="error"?(N=m.errorText)!=null?N:An.error:An[T]})(c),m,c)},onStreamingChanged(c){kr=c,ol(c),j&&Vs(rt,j.getMessages(),te),c||un(!0),fs()},onVoiceStatusChanged(c){var m,h;if(i.emit("voice:status",{status:c,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":Kr(),ys();break;case"processing":Kr(),uh();break;case"speaking":Kr(),mh();break;default:c==="idle"&&j.isBargeInActive()?(Kr(),ys(),B==null||B.setAttribute("aria-label","End voice session")):(ut.active=!1,Kr(),nr("system"),Bn());break}},onArtifactsState(c){_n=c,Hn(),tt()}}),St.current=j;let al=null;if(j.onReadAloudChange((c,m)=>{var T;oo=c,so=m,ao();let h=c!=null?c:al;c&&(al=c);let b=h&&(T=j.getMessages().find(D=>D.id===h))!=null?T:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(al=null)}),ds=!0,((_d=(Fd=r.voiceRecognition)==null?void 0:Fd.provider)==null?void 0:_d.type)==="runtype")try{j.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&j.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||r.onSSEEvent)&&j.setSSEEventCallback((c,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,c,m),G==null||G.processEvent(c,m),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(c=>{var m,h,b;if(c){if(c.metadata&&(p=lc(c.metadata),P.syncFromMetadata()),(m=c.messages)!=null&&m.length){No=!0;try{j.hydrateMessages(c.messages)}finally{No=!1}}(h=c.artifacts)!=null&&h.length&&j.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Pc=()=>{var m,h,b;!H()||O||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||qt(!0,"auto")},Ic=c=>{var T;if(c.preventDefault(),j.isStreaming()){j.cancel(),G==null||G.reset(),we==null||we.update();return}let m=re.value.trim(),h=(T=At==null?void 0:At.hasAttachments())!=null?T:!1;if(!m&&!h)return;Pc();let b;h&&(b=[],b.push(...At.getContentParts()),m&&b.push(ma(m))),re.value="",re.style.height="auto",_a(),j.sendMessage(m,{contentParts:b}),h&&At.clearAttachments()},lh=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},il={...vi},ll=!1,_a=()=>{il={...vi}},ch=()=>j.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),dh=c=>{if(!re)return;ll=!0,re.value=c,re.dispatchEvent(new Event("input",{bubbles:!0})),ll=!1;let m=re.value.length;re.setSelectionRange(m,m)},Rc=()=>{ll||_a()},Wc=c=>{if(re){if(lh()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=re.selectionStart===0&&re.selectionEnd===0,h=mg({direction:c.key==="ArrowUp"?"up":"down",history:ch(),currentValue:re.value,atStart:m,state:il});if(il=h.state,h.handled){c.preventDefault(),h.value!==void 0&&dh(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(j.isStreaming()){c.preventDefault();return}_a(),c.preventDefault(),je.click()}}},Hc=c=>{c.key!=="Escape"||c.isComposing||j.isStreaming()&&c.composedPath().includes(Ce)&&(j.cancel(),G==null||G.reset(),we==null||we.update(),_a(),c.preventDefault(),c.stopImmediatePropagation())},Bc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let m=lx(c.clipboardData);m.length!==0&&(c.preventDefault(),await At.handleFiles(m))},rr=null,Rr=!1,hs=null,dt=null,Dc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$a=(c="user")=>{var D,z,$,N,le,ce,Z;if(Rr||j.isStreaming())return;let m=Dc();if(!m)return;rr=new m;let b=(z=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?z:2e3;rr.continuous=!0,rr.interimResults=!0,rr.lang="en-US";let T=re.value;rr.onresult=be=>{let Oe="",Ae="";for(let Ue=0;Ue<be.results.length;Ue++){let pt=be.results[Ue],ot=pt[0].transcript;pt.isFinal?Oe+=ot+" ":Ae=ot}let et=T+Oe+Ae;re.value=et,hs&&clearTimeout(hs),(Oe||Ae)&&(hs=window.setTimeout(()=>{let Ue=re.value.trim();Ue&&rr&&Rr&&(uo(),re.value="",re.style.height="auto",j.sendMessage(Ue,{viaVoice:!0}))},b))},rr.onerror=be=>{be.error!=="no-speech"&&uo()},rr.onend=()=>{if(Rr){let be=re.value.trim();be&&be!==T.trim()&&(re.value="",re.style.height="auto",j.sendMessage(be,{viaVoice:!0})),uo()}};try{if(rr.start(),Rr=!0,ut.active=!0,c!=="system"&&(ut.manuallyDeactivated=!1),nr(c),Bn(),B){let be=($=r.voiceRecognition)!=null?$:{};dt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(N=be.iconName)!=null?N:"mic",iconSize:parseFloat((Z=(ce=be.iconSize)!=null?ce:(le=r.sendButton)==null?void 0:le.size)!=null?Z:"40")||24};let Oe=be.recordingBackgroundColor,Ae=be.recordingIconColor,et=be.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let Ue=B.querySelector("svg");Ue&&Ue.setAttribute("stroke",Ae)}et&&(B.style.borderColor=et),B.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(c="user")=>{if(Rr){if(Rr=!1,hs&&(clearTimeout(hs),hs=null),rr){try{rr.stop()}catch{}rr=null}if(ut.active=!1,nr(c),Bn(),B){if(B.classList.remove("persona-voice-recording"),dt){B.style.backgroundColor=dt.backgroundColor,B.style.color=dt.color,B.style.borderColor=dt.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",dt.color||"currentColor"),dt=null}B.setAttribute("aria-label","Start voice recognition")}}},ph=(c,m)=>{var ot,Ie,Le,qe,Ke,ht,R,Be,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ot=c==null?void 0:c.provider)==null?void 0:ot.type)==="runtype",T=((Ie=c==null?void 0:c.provider)==null?void 0:Ie.type)==="custom";if(!(h||b||T))return null;let z=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=(Le=c==null?void 0:c.iconName)!=null?Le:"mic",le=(qe=m==null?void 0:m.size)!=null?qe:"40px",ce=(Ke=c==null?void 0:c.iconSize)!=null?Ke:le,Z=parseFloat(ce)||24,be=(ht=c==null?void 0:c.backgroundColor)!=null?ht:m==null?void 0:m.backgroundColor,Oe=(R=c==null?void 0:c.iconColor)!=null?R:m==null?void 0:m.textColor;$.style.width=ce,$.style.height=ce,$.style.minWidth=ce,$.style.minHeight=ce,$.style.fontSize="18px",$.style.lineHeight="1",Oe?$.style.color=Oe:$.style.color="var(--persona-text, #111827)";let et=ge(N,Z,Oe||"currentColor",1.5);et?$.appendChild(et):$.textContent="\u{1F3A4}",be?$.style.backgroundColor=be:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),z.appendChild($);let Ue=(Be=c==null?void 0:c.tooltipText)!=null?Be:"Start voice recognition";if(((Re=c==null?void 0:c.showTooltip)!=null?Re:!1)&&Ue){let me=y("div","persona-send-button-tooltip");me.textContent=Ue,z.appendChild(me)}return{micButton:$,micButtonWrapper:z}},cl=()=>{var m,h,b,T,D;if(!B||dt)return;let c=(m=r.voiceRecognition)!=null?m:{};dt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((D=(T=c.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},dl=(c,m)=>{var D,z,$,N,le;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let b=(le=dt==null?void 0:dt.iconSize)!=null?le:parseFloat((N=($=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?$:(z=r.sendButton)==null?void 0:z.size)!=null?N:"40")||24,T=ge(c,b,m,1.5);T&&B.appendChild(T)},ja=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ys=()=>{var T;if(!B)return;cl();let c=(T=r.voiceRecognition)!=null?T:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(ja(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=B.querySelector("svg");D&&D.setAttribute("stroke",h)}b&&(B.style.borderColor=b),B.setAttribute("aria-label","Stop voice recognition")},uh=()=>{var $,N,le,ce,Z,be,Oe,Ae;if(!B)return;cl();let c=($=r.voiceRecognition)!=null?$:{},m=j.getVoiceInterruptionMode(),h=(N=c.processingIconName)!=null?N:"loader",b=(ce=(le=c.processingIconColor)!=null?le:dt==null?void 0:dt.color)!=null?ce:"",T=(be=(Z=c.processingBackgroundColor)!=null?Z:dt==null?void 0:dt.backgroundColor)!=null?be:"",D=(Ae=(Oe=c.processingBorderColor)!=null?Oe:dt==null?void 0:dt.borderColor)!=null?Ae:"";ja(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=T,B.style.borderColor=D;let z=b||"currentColor";B.style.color=z,dl(h,z),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},mh=()=>{var le,ce,Z,be,Oe,Ae,et,Ue,pt,ot,Ie,Le;if(!B)return;cl();let c=(le=r.voiceRecognition)!=null?le:{},m=j.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ce=c.speakingIconName)!=null?ce:h,T=(Ae=c.speakingIconColor)!=null?Ae:m==="barge-in"?(be=(Z=c.recordingIconColor)!=null?Z:dt==null?void 0:dt.color)!=null?be:"":(Oe=dt==null?void 0:dt.color)!=null?Oe:"",D=(pt=c.speakingBackgroundColor)!=null?pt:m==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Ue=dt==null?void 0:dt.backgroundColor)!=null?Ue:"",z=(Le=c.speakingBorderColor)!=null?Le:m==="barge-in"?(ot=c.recordingBorderColor)!=null?ot:"":(Ie=dt==null?void 0:dt.borderColor)!=null?Ie:"";ja(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=D,B.style.borderColor=z;let $=T||"currentColor";B.style.color=$,dl(b,$);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",N),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},Kr=()=>{var c,m,h;B&&(ja(),dt&&(B.style.backgroundColor=(c=dt.backgroundColor)!=null?c:"",B.style.color=(m=dt.color)!=null?m:"",B.style.borderColor=(h=dt.borderColor)!=null?h:"",dl(dt.iconName,dt.color||"currentColor"),dt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ua=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let h=j.getVoiceStatus(),b=j.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){j.stopVoicePlayback();return}if(j.isBargeInActive()){j.stopVoicePlayback(),j.deactivateBargeIn().then(()=>{ut.active=!1,ut.manuallyDeactivated=!0,Bn(),nr("user"),Kr()});return}j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),ut.manuallyDeactivated=!j.isVoiceActive(),Bn(),nr("user"),j.isVoiceActive()?ys():Kr()});return}if(Rr){let h=re.value.trim();ut.manuallyDeactivated=!0,Bn(),uo("user"),h&&(re.value="",re.style.height="auto",j.sendMessage(h))}else ut.manuallyDeactivated=!1,Bn(),$a("user")};Cr=Ua,B&&(B.addEventListener("click",Ua),gt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(j.isVoiceActive()&&j.toggleVoice(),Kr()):uo("system"),B&&B.removeEventListener("click",Ua)}));let gh=i.on("assistant:complete",()=>{qs&&(ut.active||ut.manuallyDeactivated||qs==="assistant"&&!ut.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!ut.active&&!ut.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),nr("auto"),j.isVoiceActive()&&ys()}):$a("auto"))},600))});gt.push(gh);let fh=i.on("action:resubmit",()=>{setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)});gt.push(fh);let Nc=()=>{qt(!O,"user")},en=null,ln=null;if(L&&!H()){let{instance:c,element:m}=Kl({config:r,plugins:o,onToggle:Nc});en=c,c||(ln=m)}en?e.appendChild(en.element):ln&&e.appendChild(ln),Xs(),ls(),Lc(),ol(j.isStreaming()),Ct()==="follow"?un(!0):Vr(),Fa(),I&&(!L||H()?setTimeout(()=>sl(),0):O&&setTimeout(()=>sl(),200));let Qs=()=>{var N,le,ce,Z,be,Oe,Ae,et,Ue,pt,ot,Ie,Le,qe,Ke,ht,R,Be,Re,me,Nt,Ht;if(H()){Mn(),Xs();return}let c=on(r),m=(le=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?le:!1,h=c||m||((Z=(ce=r.launcher)==null?void 0:ce.fullHeight)!=null?Z:!1),b=(be=e.ownerDocument.defaultView)!=null?be:window,T=(Ae=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ae:!0,D=(Ue=(et=r.launcher)==null?void 0:et.mobileBreakpoint)!=null?Ue:640,z=b.innerWidth<=D,$=T&&z&&L;try{if($){Tr(),To(e,r);return}if(U&&(U=!1,Tr(),To(e,r)),!L&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let Jt=(ot=(pt=r==null?void 0:r.launcher)==null?void 0:pt.width)!=null?ot:r==null?void 0:r.launcherWidth,yt=Jt!=null?Jt:Xn;J.style.width=yt,J.style.maxWidth=yt}if(ye(),!h){let Jt=b.innerHeight,yt=64,zt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Vn=Math.max(200,Jt-yt),tn=Math.min(640,Vn),Xe=Math.max(200,tn-zt);J.style.height=`${Xe}px`}}finally{if(Mn(),Xs(),O&&L){let yt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((ht=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?ht:640),zt=(Be=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?Be:!1,Vn=(me=(Re=r.launcher)==null?void 0:Re.mobileFullscreen)!=null?me:!0,tn=on(r)&&Vn&&yt,Xe=zt||Vn&&yt&&L||tn;if(Xe&&!an){let Mt=e.getRootNode(),rn=Mt instanceof ShadowRoot?Mt.host:e.closest(".persona-host");rn&&!sn&&(sn=$l(rn,(Ht=(Nt=r.launcher)==null?void 0:Nt.zIndex)!=null?Ht:Sn)),an=jl(e.ownerDocument)}else Xe||(sn==null||sn(),sn=null,an==null||an(),an=null)}}};Qs();let Oc=($d=e.ownerDocument.defaultView)!=null?$d:window;if(Oc.addEventListener("resize",Qs),gt.push(()=>Oc.removeEventListener("resize",Qs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Mn()});c.observe(Ne),gt.push(()=>c.disconnect())}qn=Se.scrollTop;let Fc=Zr(Se),hh=()=>{let c=Se.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:Se.ownerDocument.getSelection()},pl=()=>xg(hh(),Se),_c=()=>{let c=Se.scrollTop,m=Zr(Se),h=m<Fc;if(Fc=m,Ct()!=="follow"){qn=c,at();return}let{action:b,nextLastScrollTop:T}=Ci({following:Un.isFollowing(),currentScrollTop:c,lastScrollTop:qn,nearBottom:es(Se,us),userScrollThreshold:Na,isAutoScrolling:gr||Do||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qn=T,b==="resume"){pl()||Dn();return}b==="pause"&&zs()};if(Se.addEventListener("scroll",_c,{passive:!0}),gt.push(()=>Se.removeEventListener("scroll",_c)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Zf()});c.observe(rt),c.observe(Se),gt.push(()=>c.disconnect())}let $c=()=>{Ct()==="follow"&&Un.isFollowing()&&pl()&&zs()},jc=Se.ownerDocument;jc.addEventListener("selectionchange",$c),gt.push(()=>{jc.removeEventListener("selectionchange",$c)});let Uc=c=>{if(Ct()!=="follow")return;let m=Ai({following:Un.isFollowing(),deltaY:c.deltaY,nearBottom:es(Se,us),resumeWhenNearBottom:!0});m==="pause"?zs():m==="resume"&&!pl()&&Dn()};Se.addEventListener("wheel",Uc,{passive:!0}),gt.push(()=>Se.removeEventListener("wheel",Uc)),$t.addEventListener("click",()=>{xn(),Se.scrollTop=Se.scrollHeight,qn=Se.scrollTop,Dn(),un(!0),at()}),gt.push(()=>$t.remove()),gt.push(()=>{Q(),xn()});let qc=()=>{S&&(Mr&&(S.removeEventListener("click",Mr),Mr=null),F()?(S.style.display="",Mr=()=>{qt(!1,"user")},S.addEventListener("click",Mr)):S.style.display="none")};qc(),(()=>{let{clearChatButton:c}=ze;c&&c.addEventListener("click",()=>{j.clearMessages(),Lr.clear(),Dn(),vo(ze.composerOverlay);try{localStorage.removeItem(js),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${js}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==js)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),l!=null&&l.clear)try{let h=l.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},P.syncFromMetadata(),K==null||K.clear(),G==null||G.reset(),we==null||we.update()})})(),Dt&&Dt.addEventListener("submit",Ic),re==null||re.addEventListener("keydown",Wc),re==null||re.addEventListener("input",Rc),re==null||re.addEventListener("paste",Bc);let zc=(jd=e.ownerDocument)!=null?jd:document;zc.addEventListener("keydown",Hc,!0);let Vc="persona-attachment-drop-active",Ys=0,ul=()=>{Ys=0,Ce.classList.remove(Vc)},bs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&At!==null},Kc=c=>{!Ji(c.dataTransfer)||!bs()||(Ys++,Ys===1&&Ce.classList.add(Vc))},Gc=c=>{!Ji(c.dataTransfer)||!bs()||(Ys--,Ys<=0&&ul())},Jc=c=>{!Ji(c.dataTransfer)||!bs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Xc=c=>{var h;if(!Ji(c.dataTransfer)||!bs())return;c.preventDefault(),c.stopPropagation(),ul();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&At.handleFiles(m)},mo=!0;Ce.addEventListener("dragenter",Kc,mo),Ce.addEventListener("dragleave",Gc,mo),e.addEventListener("dragover",Jc,mo),e.addEventListener("drop",Xc,mo);let qa=e.ownerDocument,Qc=c=>{bs()&&c.preventDefault()},Yc=c=>{bs()&&c.preventDefault()};qa.addEventListener("dragover",Qc),qa.addEventListener("drop",Yc),gt.push(()=>{Dt&&Dt.removeEventListener("submit",Ic),re==null||re.removeEventListener("keydown",Wc),re==null||re.removeEventListener("input",Rc),re==null||re.removeEventListener("paste",Bc),zc.removeEventListener("keydown",Hc,!0)}),gt.push(()=>{Ce.removeEventListener("dragenter",Kc,mo),Ce.removeEventListener("dragleave",Gc,mo),e.removeEventListener("dragover",Jc,mo),e.removeEventListener("drop",Xc,mo),qa.removeEventListener("dragover",Qc),qa.removeEventListener("drop",Yc),ul()}),gt.push(()=>{j.cancel()}),en?gt.push(()=>{en==null||en.destroy()}):ln&>.push(()=>{ln==null||ln.remove()});let nn={update(c){var jt,gn,Gn,Hr,fn,hn,ar,ho,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,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;let m=r.toolCall,h=r.messageActions,b=(jt=r.layout)==null?void 0:jt.messages,T=r.colorScheme,D=r.loadingIndicator,z=r.iterationDisplay,$=(gn=r.features)==null?void 0:gn.showReasoning,N=(Gn=r.features)==null?void 0:Gn.showToolCalls,le=(Hr=r.features)==null?void 0:Hr.toolCallDisplay,ce=(fn=r.features)==null?void 0:fn.reasoningDisplay;r={...r,...c},Tr(),To(e,r),_i(e,r),$i(e,r),Hn(),r.colorScheme!==T&&Us();let Z=Ia.getForInstance(r.plugins);o.length=0,o.push(...Z),L=(ar=(hn=r.launcher)==null?void 0:hn.enabled)!=null?ar:!0,k=(Jd=(ho=r.launcher)==null?void 0:ho.autoExpand)!=null?Jd:!1,ve=(Qd=(Xd=r.features)==null?void 0:Xd.showReasoning)!=null?Qd:!0,ke=(Zd=(Yd=r.features)==null?void 0:Yd.showToolCalls)!=null?Zd:!0,xe=(tp=(ep=r.features)==null?void 0:ep.scrollToBottom)!=null?tp:{};let be=Ct();pe=(rp=(np=r.features)==null?void 0:np.scrollBehavior)!=null?rp:{},be!==Ct()&&(xn(),Dn()),dr(),at();let Oe=se;if(se=(sp=(op=r.features)==null?void 0:op.showEventStreamToggle)!=null?sp:!1,se&&!Oe){if(K||(He=new La(ae),K=new ka(Fe,He),G=G!=null?G:new Pa,He.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),j.setSSEEventCallback((oe,Tt)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,oe,Tt),G==null||G.processEvent(oe,Tt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:oe,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!mt&&Pe){let oe=(ip=(ap=r.features)==null?void 0:ap.eventStream)==null?void 0:ip.classNames,Tt="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"+(oe!=null&&oe.toggleButton?" "+oe.toggleButton:"");mt=y("button",Tt),mt.style.width="28px",mt.style.height="28px",mt.style.color=Rn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Vt=ge("activity","18px","currentColor",1.5);Vt&&mt.appendChild(Vt);let st=ze.clearChatButtonWrapper,Lt=ze.closeButtonWrapper,cn=st||Lt;cn&&cn.parentNode===Pe?Pe.insertBefore(mt,cn):Pe.appendChild(mt),mt.addEventListener("click",()=>{X?pr():Fr()})}}else!se&&Oe&&(pr(),mt&&(mt.remove(),mt=null),K==null||K.clear(),He==null||He.destroy(),K=null,He=null,G==null||G.reset(),G=null);if(((lp=r.launcher)==null?void 0:lp.enabled)===!1&&en&&(en.destroy(),en=null),((cp=r.launcher)==null?void 0:cp.enabled)===!1&&ln&&(ln.remove(),ln=null),((dp=r.launcher)==null?void 0:dp.enabled)!==!1&&!en&&!ln){let{instance:oe,element:Tt}=Kl({config:r,plugins:o,onToggle:Nc});en=oe,oe||(ln=Tt),e.appendChild(Tt)}en&&en.update(r),Me&&((pp=r.launcher)==null?void 0:pp.title)!==void 0&&(Me.textContent=r.launcher.title),De&&((up=r.launcher)==null?void 0:up.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Ae=(mp=r.layout)==null?void 0:mp.header;if((Ae==null?void 0:Ae.layout)!==_&&Pe){let oe=Ae?Bs(r,Ae,{showClose:F(),onClose:()=>qt(!1,"user")}):eo({config:r,showClose:F(),onClose:()=>qt(!1,"user")});Ze.replaceHeader(oe),Pe=Ze.header.element,ne=Ze.header.iconHolder,Me=Ze.header.headerTitle,De=Ze.header.headerSubtitle,S=Ze.header.closeButton,_=Ae==null?void 0:Ae.layout}else if(Ae&&(ne&&(ne.style.display=Ae.showIcon===!1?"none":""),Me&&(Me.style.display=Ae.showTitle===!1?"none":""),De&&(De.style.display=Ae.showSubtitle===!1?"none":""),S&&(S.style.display=Ae.showCloseButton===!1?"none":""),ze.clearChatButtonWrapper)){let oe=Ae.showClearChat;if(oe!==void 0){ze.clearChatButtonWrapper.style.display=oe?"":"none";let{closeButtonWrapper:Tt}=ze;Tt&&!Tt.classList.contains("persona-absolute")&&(oe?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let Ue=((gp=r.layout)==null?void 0:gp.showHeader)!==!1;Pe&&(Pe.style.display=Ue?"":"none");let pt=((fp=r.layout)==null?void 0:fp.showFooter)!==!1;Ne&&(Ne.style.display=pt?"":"none"),Mn(),at(),L!==W?L?qt(k,"auto"):(O=!0,Xs()):k!==C&&qt(k,"auto"),C=k,W=L,Qs(),qc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(m),qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((hp=r.layout)==null?void 0:hp.messages)!==JSON.stringify(b),ht=((yp=r.loadingIndicator)==null?void 0:yp.render)!==(D==null?void 0:D.render)||((bp=r.loadingIndicator)==null?void 0:bp.renderIdle)!==(D==null?void 0:D.renderIdle)||((xp=r.loadingIndicator)==null?void 0:xp.showBubble)!==(D==null?void 0:D.showBubble),R=r.iterationDisplay!==z,Be=((wp=(vp=r.features)==null?void 0:vp.showReasoning)!=null?wp:!0)!==($!=null?$:!0)||((Ap=(Cp=r.features)==null?void 0:Cp.showToolCalls)!=null?Ap:!0)!==(N!=null?N:!0)||JSON.stringify((Sp=r.features)==null?void 0:Sp.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify((Tp=r.features)==null?void 0:Tp.reasoningDisplay)!==JSON.stringify(ce);(Le||qe||Ke||ht||R||Be)&&j&&(cs++,Vs(rt,j.getMessages(),te));let me=(Ep=r.launcher)!=null?Ep:{},Nt=(Mp=me.headerIconHidden)!=null?Mp:!1,Ht=(Lp=(kp=r.layout)==null?void 0:kp.header)==null?void 0:Lp.showIcon,Jt=Nt||Ht===!1,yt=me.headerIconName,zt=(Pp=me.headerIconSize)!=null?Pp:"48px";if(ne){let oe=Ce.querySelector(".persona-border-b-persona-divider"),Tt=oe==null?void 0:oe.querySelector(".persona-flex-col");if(Jt)ne.style.display="none",oe&&Tt&&!oe.contains(Tt)&&oe.insertBefore(Tt,oe.firstChild);else{if(ne.style.display="",ne.style.height=zt,ne.style.width=zt,oe&&Tt&&(oe.contains(ne)?ne.nextSibling!==Tt&&(ne.remove(),oe.insertBefore(ne,Tt)):oe.insertBefore(ne,Tt)),yt){let st=parseFloat(zt)||24,Lt=ge(yt,st*.6,"currentColor",1);Lt?ne.replaceChildren(Lt):ne.textContent=(Ip=me.agentIconText)!=null?Ip:"\u{1F4AC}"}else if(me.iconUrl){let st=ne.querySelector("img");if(st)st.src=me.iconUrl,st.style.height=zt,st.style.width=zt;else{let Lt=document.createElement("img");Lt.src=me.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=zt,Lt.style.width=zt,ne.replaceChildren(Lt)}}else{let st=ne.querySelector("svg"),Lt=ne.querySelector("img");(st||Lt)&&ne.replaceChildren(),ne.textContent=(Rp=me.agentIconText)!=null?Rp:"\u{1F4AC}"}let Vt=ne.querySelector("img");Vt&&(Vt.style.height=zt,Vt.style.width=zt)}}let Vn=(Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showTitle,tn=(Dp=(Bp=r.layout)==null?void 0:Bp.header)==null?void 0:Dp.showSubtitle;if(Me&&(Me.style.display=Vn===!1?"none":""),De&&(De.style.display=tn===!1?"none":""),S){((Op=(Np=r.layout)==null?void 0:Np.header)==null?void 0:Op.showCloseButton)===!1?S.style.display="none":S.style.display="";let Tt=(Fp=me.closeButtonSize)!=null?Fp:"32px",Vt=(_p=me.closeButtonPlacement)!=null?_p:"inline";S.style.height=Tt,S.style.width=Tt;let{closeButtonWrapper:st}=ze,Lt=Vt==="top-right",cn=st==null?void 0:st.classList.contains("persona-absolute");if(st&&Lt!==cn)if(st.remove(),Lt)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(st);else{let it=(jp=($p=me.clearChat)==null?void 0:$p.placement)!=null?jp:"inline",dn=(qp=(Up=me.clearChat)==null?void 0:Up.enabled)!=null?qp:!0;st.className=dn&&it==="inline"?"":"persona-ml-auto";let Nn=Ce.querySelector(".persona-border-b-persona-divider");Nn&&Nn.appendChild(st)}if(S.style.color=me.closeButtonColor||Rn.actionIconColor,me.closeButtonBackgroundColor?(S.style.backgroundColor=me.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let it=me.closeButtonBorderWidth||"0px",dn=me.closeButtonBorderColor||"transparent";S.style.border=`${it} solid ${dn}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");me.closeButtonBorderRadius?(S.style.borderRadius=me.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(S.style.paddingLeft=me.closeButtonPaddingX,S.style.paddingRight=me.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),me.closeButtonPaddingY?(S.style.paddingTop=me.closeButtonPaddingY,S.style.paddingBottom=me.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let Cn=(zp=me.closeButtonIconName)!=null?zp:"x",hr=(Vp=me.closeButtonIconText)!=null?Vp:"\xD7";S.innerHTML="";let In=ge(Cn,"28px","currentColor",1);In?S.appendChild(In):S.textContent=hr;let Zt=(Kp=me.closeButtonTooltipText)!=null?Kp:"Close chat",Jn=(Gp=me.closeButtonShowTooltip)!=null?Gp:!0;if(S.setAttribute("aria-label",Zt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),Jn&&Zt)){let it=null,dn=()=>{if(it||!S)return;let qo=S.ownerDocument,Zs=qo.body;if(!Zs)return;it=Dr(qo,"div","persona-clear-chat-tooltip"),it.textContent=Zt;let ea=Dr(qo,"div");ea.className="persona-clear-chat-tooltip-arrow",it.appendChild(ea);let zo=S.getBoundingClientRect();it.style.position="fixed",it.style.zIndex=String(Eo),it.style.left=`${zo.left+zo.width/2}px`,it.style.top=`${zo.top-8}px`,it.style.transform="translate(-50%, -100%)",Zs.appendChild(it)},Nn=()=>{it&&it.parentNode&&(it.parentNode.removeChild(it),it=null)};st.addEventListener("mouseenter",dn),st.addEventListener("mouseleave",Nn),S.addEventListener("focus",dn),S.addEventListener("blur",Nn),st._cleanupTooltip=()=>{Nn(),st&&(st.removeEventListener("mouseenter",dn),st.removeEventListener("mouseleave",Nn)),S&&(S.removeEventListener("focus",dn),S.removeEventListener("blur",Nn))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Mt}=ze;if(Xe){let oe=(Jp=me.clearChat)!=null?Jp:{},Tt=(Xp=oe.enabled)!=null?Xp:!0,Vt=(Yp=(Qp=r.layout)==null?void 0:Qp.header)==null?void 0:Yp.showClearChat,st=Vt!==void 0?Vt:Tt,Lt=(Zp=oe.placement)!=null?Zp:"inline";if(Mt){Mt.style.display=st?"":"none";let{closeButtonWrapper:cn}=ze;!H()&&cn&&!cn.classList.contains("persona-absolute")&&(st?cn.classList.remove("persona-ml-auto"):cn.classList.add("persona-ml-auto"));let Cn=Lt==="top-right",hr=Mt.classList.contains("persona-absolute");if(!H()&&Cn!==hr&&st){if(Mt.remove(),Cn)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",Ce.style.position="relative",Ce.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let Zt=Ce.querySelector(".persona-border-b-persona-divider"),Jn=ze.closeButtonWrapper;Zt&&Jn&&Jn.parentElement===Zt?Zt.insertBefore(Mt,Jn):Zt&&Zt.appendChild(Mt)}let In=ze.closeButtonWrapper;In&&!In.classList.contains("persona-absolute")&&(Cn?In.classList.add("persona-ml-auto"):In.classList.remove("persona-ml-auto"))}}if(st){if(!H()){let it=(eu=oe.size)!=null?eu:"32px";Xe.style.height=it,Xe.style.width=it}let cn=(tu=oe.iconName)!=null?tu:"refresh-cw",Cn=(nu=oe.iconColor)!=null?nu:"";Xe.style.color=Cn||Rn.actionIconColor,Xe.innerHTML="";let hr=H()?"14px":"20px",In=ge(cn,hr,"currentColor",2);if(In&&Xe.appendChild(In),oe.backgroundColor?(Xe.style.backgroundColor=oe.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),oe.borderWidth||oe.borderColor){let it=oe.borderWidth||"0px",dn=oe.borderColor||"transparent";Xe.style.border=`${it} solid ${dn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");oe.borderRadius?(Xe.style.borderRadius=oe.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),oe.paddingX?(Xe.style.paddingLeft=oe.paddingX,Xe.style.paddingRight=oe.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),oe.paddingY?(Xe.style.paddingTop=oe.paddingY,Xe.style.paddingBottom=oe.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Zt=(ru=oe.tooltipText)!=null?ru:"Clear chat",Jn=(ou=oe.showTooltip)!=null?ou:!0;if(Xe.setAttribute("aria-label",Zt),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),Jn&&Zt)){let it=null,dn=()=>{if(it||!Xe)return;let qo=Xe.ownerDocument,Zs=qo.body;if(!Zs)return;it=Dr(qo,"div","persona-clear-chat-tooltip"),it.textContent=Zt;let ea=Dr(qo,"div");ea.className="persona-clear-chat-tooltip-arrow",it.appendChild(ea);let zo=Xe.getBoundingClientRect();it.style.position="fixed",it.style.zIndex=String(Eo),it.style.left=`${zo.left+zo.width/2}px`,it.style.top=`${zo.top-8}px`,it.style.transform="translate(-50%, -100%)",Zs.appendChild(it)},Nn=()=>{it&&it.parentNode&&(it.parentNode.removeChild(it),it=null)};Mt.addEventListener("mouseenter",dn),Mt.addEventListener("mouseleave",Nn),Xe.addEventListener("focus",dn),Xe.addEventListener("blur",Nn),Mt._cleanupTooltip=()=>{Nn(),Mt&&(Mt.removeEventListener("mouseenter",dn),Mt.removeEventListener("mouseleave",Nn)),Xe&&(Xe.removeEventListener("focus",dn),Xe.removeEventListener("blur",Nn))}}}}let rn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ra],sr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[as.message,as.messageAndClick];P=Wa({parsers:rn,handlers:sr,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),te=mf(r,P,ue),j.updateConfig(r),Vs(rt,j.getMessages(),te),ls(),Lc(),ol(j.isStreaming());let Kn=((su=r.voiceRecognition)==null?void 0:su.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((iu=(au=r.voiceRecognition)==null?void 0:au.provider)==null?void 0:iu.type)==="runtype";if(Kn&&(_o||$o))if(!B||!Y){let oe=ph(r.voiceRecognition,r.sendButton);oe&&(B=oe.micButton,Y=oe.micButtonWrapper,It.insertBefore(Y,yn),B.addEventListener("click",Ua),B.disabled=j.isStreaming())}else{let oe=(lu=r.voiceRecognition)!=null?lu:{},Tt=(cu=r.sendButton)!=null?cu:{},Vt=(du=oe.iconName)!=null?du:"mic",st=(pu=Tt.size)!=null?pu:"40px",Lt=(uu=oe.iconSize)!=null?uu:st,cn=parseFloat(Lt)||24;B.style.width=Lt,B.style.height=Lt,B.style.minWidth=Lt,B.style.minHeight=Lt;let Cn=(gu=(mu=oe.iconColor)!=null?mu:Tt.textColor)!=null?gu:"currentColor";B.innerHTML="";let hr=ge(Vt,cn,Cn,2);hr?B.appendChild(hr):B.textContent="\u{1F3A4}";let In=(fu=oe.backgroundColor)!=null?fu:Tt.backgroundColor;In?B.style.backgroundColor=In:B.style.backgroundColor="",Cn?B.style.color=Cn:B.style.color="var(--persona-text, #111827)",oe.borderWidth?(B.style.borderWidth=oe.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),oe.borderColor?B.style.borderColor=oe.borderColor:B.style.borderColor="",oe.paddingX?(B.style.paddingLeft=oe.paddingX,B.style.paddingRight=oe.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),oe.paddingY?(B.style.paddingTop=oe.paddingY,B.style.paddingBottom=oe.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Zt=Y==null?void 0:Y.querySelector(".persona-send-button-tooltip"),Jn=(hu=oe.tooltipText)!=null?hu:"Start voice recognition";if(((yu=oe.showTooltip)!=null?yu:!1)&&Jn)if(Zt)Zt.textContent=Jn,Zt.style.display="";else{let dn=document.createElement("div");dn.className="persona-send-button-tooltip",dn.textContent=Jn,Y==null||Y.insertBefore(dn,B)}else Zt&&(Zt.style.display="none");Y.style.display="",B.disabled=j.isStreaming()}else B&&Y&&(Y.style.display="none",((xu=(bu=r.voiceRecognition)==null?void 0:bu.provider)==null?void 0:xu.type)==="runtype"?j.isVoiceActive()&&j.toggleVoice():Rr&&uo());if(((vu=r.attachments)==null?void 0:vu.enabled)===!0)if(!ct||!Te){let oe=(wu=r.attachments)!=null?wu:{},Vt=(Au=((Cu=r.sendButton)!=null?Cu:{}).size)!=null?Au:"40px";Ut||(Ut=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Dt.insertBefore(Ut,re)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((Su=oe.allowedTypes)!=null?Su:Yr).join(","),Ye.multiple=((Tu=oe.maxFiles)!=null?Tu:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),Dt.insertBefore(Ye,re)),ct=y("div","persona-send-button-wrapper"),Te=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Te.type="button",Te.setAttribute("aria-label",(Eu=oe.buttonTooltipText)!=null?Eu:"Attach file");let st=(Mu=oe.buttonIconName)!=null?Mu:"paperclip",Lt=Vt,cn=parseFloat(Lt)||40,Cn=Math.round(cn*.6);Te.style.width=Lt,Te.style.height=Lt,Te.style.minWidth=Lt,Te.style.minHeight=Lt,Te.style.fontSize="18px",Te.style.lineHeight="1",Te.style.backgroundColor="transparent",Te.style.color="var(--persona-primary, #111827)",Te.style.border="none",Te.style.borderRadius="6px",Te.style.transition="background-color 0.15s ease",Te.addEventListener("mouseenter",()=>{Te.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Te.addEventListener("mouseleave",()=>{Te.style.backgroundColor="transparent"});let hr=ge(st,Cn,"currentColor",1.5);hr?Te.appendChild(hr):Te.textContent="\u{1F4CE}",Te.addEventListener("click",Jn=>{Jn.preventDefault(),Ye==null||Ye.click()}),ct.appendChild(Te);let In=(ku=oe.buttonTooltipText)!=null?ku:"Attach file",Zt=y("div","persona-send-button-tooltip");Zt.textContent=In,ct.appendChild(Zt),lt.append(ct),!At&&Ye&&Ut&&(At=Zo.fromConfig(oe),At.setPreviewsContainer(Ut),Ye.addEventListener("change",async()=>{At&&(Ye!=null&&Ye.files)&&(await At.handleFileSelect(Ye.files),Ye.value="")})),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(gf(oe.dropOverlay))}else{ct.style.display="";let oe=(Lu=r.attachments)!=null?Lu:{};Ye&&(Ye.accept=((Pu=oe.allowedTypes)!=null?Pu:Yr).join(","),Ye.multiple=((Iu=oe.maxFiles)!=null?Iu:4)>1),At&&At.updateConfig({allowedTypes:oe.allowedTypes,maxFileSize:oe.maxFileSize,maxFiles:oe.maxFiles})}else ct&&(ct.style.display="none"),At&&At.clearAttachments(),(Ru=Ce.querySelector(".persona-attachment-drop-overlay"))==null||Ru.remove();let Xt=(Wu=r.sendButton)!=null?Wu:{},jo=(Hu=Xt.useIcon)!=null?Hu:!1,go=(Bu=Xt.iconText)!=null?Bu:"\u2191",fo=Xt.iconName,Gr=(Du=Xt.tooltipText)!=null?Du:"Send message",Uo=(Nu=Xt.showTooltip)!=null?Nu:!1,fr=(Ou=Xt.size)!=null?Ou:"40px",Wr=Xt.backgroundColor,Qe=Xt.textColor;if(jo){if(je.style.width=fr,je.style.height=fr,je.style.minWidth=fr,je.style.minHeight=fr,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",Qe?je.style.color=Qe:je.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let oe=parseFloat(fr)||24,Tt=(Qe==null?void 0:Qe.trim())||"currentColor",Vt=ge(fo,oe,Tt,2);Vt?je.appendChild(Vt):je.textContent=go}else je.textContent=go;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wr?(je.style.backgroundColor=Wr,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(_u=(Fu=r.copy)==null?void 0:Fu.sendButtonLabel)!=null?_u:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wr?(je.style.backgroundColor=Wr,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),Qe?je.style.color=Qe:je.classList.add("persona-text-white");Xt.borderWidth?(je.style.borderWidth=Xt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Xt.borderColor?je.style.borderColor=Xt.borderColor:je.style.borderColor="",Xt.paddingX?(je.style.paddingLeft=Xt.paddingX,je.style.paddingRight=Xt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Xt.paddingY?(je.style.paddingTop=Xt.paddingY,je.style.paddingBottom=Xt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Ot=yn==null?void 0:yn.querySelector(".persona-send-button-tooltip");if(Uo&&Gr)if(Ot)Ot.textContent=Gr,Ot.style.display="";else{let oe=document.createElement("div");oe.className="persona-send-button-tooltip",oe.textContent=Gr,yn==null||yn.insertBefore(oe,je)}else Ot&&(Ot.style.display="none");let Kt=(zu=($u=r.layout)==null?void 0:$u.contentMaxWidth)!=null?zu:H()?(qu=(Uu=(ju=r.launcher)==null?void 0:ju.composerBar)==null?void 0:Uu.contentMaxWidth)!=null?qu:"720px":void 0;Kt?(rt.style.maxWidth=Kt,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%",Dt&&(Dt.style.maxWidth=Kt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),_t&&(_t.style.maxWidth=Kt,_t.style.marginLeft="auto",_t.style.marginRight="auto")):(rt.style.maxWidth="",rt.style.marginLeft="",rt.style.marginRight="",rt.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),_t&&(_t.style.maxWidth="",_t.style.marginLeft="",_t.style.marginRight=""));let Ft=(Vu=r.statusIndicator)!=null?Vu:{},Qt=(Ku=Ft.visible)!=null?Ku:!0;if(Yt.style.display=Qt?"":"none",j){let oe=j.getStatus();Pt(Yt,(Vt=>{var st,Lt,cn,Cn;return Vt==="idle"?(st=Ft.idleText)!=null?st:An.idle:Vt==="connecting"?(Lt=Ft.connectingText)!=null?Lt:An.connecting:Vt==="connected"?(cn=Ft.connectedText)!=null?cn:An.connected:Vt==="error"?(Cn=Ft.errorText)!=null?Cn:An.error:An[Vt]})(oe),Ft,oe)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kt=Ft.align==="left"?"persona-text-left":Ft.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(kt)},open(){F()&&qt(!0,"api")},close(){F()&&qt(!1,"api")},toggle(){F()&&qt(!O,"api")},clearChat(){kn=!1,j.clearMessages(),Lr.clear(),Dn();try{localStorage.removeItem(js),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${js}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==js)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 c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),l!=null&&l.clear)try{let m=l.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(),G==null||G.reset(),we==null||we.update()},setMessage(c){return!re||j.isStreaming()?!1:(!O&&F()&&qt(!0,"system"),re.value=c,re.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(j.isStreaming())return!1;let m=(c==null?void 0:c.trim())||re.value.trim();return m?(!O&&F()&&qt(!0,"system"),re.value="",re.style.height="auto",j.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return j.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(j.isVoiceActive()||(!O&&F()&&qt(!0,"system"),ut.manuallyDeactivated=!1,Bn(),j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),nr("user"),j.isVoiceActive()&&ys()})),!0):Rr?!0:Dc()?(!O&&F()&&qt(!0,"system"),ut.manuallyDeactivated=!1,Bn(),$a("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.isVoiceActive()?(j.toggleVoice().then(()=>{ut.active=!1,ut.manuallyDeactivated=!0,Bn(),nr("user"),Kr()}),!0):!1:Rr?(ut.manuallyDeactivated=!0,Bn(),uo("user"),!0):!1},injectMessage(c){return!O&&F()&&qt(!0,"system"),j.injectMessage(c)},injectAssistantMessage(c){!O&&F()&&qt(!0,"system");let m=j.injectAssistantMessage(c);return ee&&(ee=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)),m},injectUserMessage(c){return!O&&F()&&qt(!0,"system"),j.injectUserMessage(c)},injectSystemMessage(c){return!O&&F()&&qt(!0,"system"),j.injectSystemMessage(c)},injectMessageBatch(c){return!O&&F()&&qt(!0,"system"),j.injectMessageBatch(c)},injectComponentDirective(c){return!O&&F()&&qt(!0,"system"),j.injectComponentDirective(c)},injectTestMessage(c){!O&&F()&&qt(!0,"system"),j.injectTestEvent(c)},async connectStream(c,m){return j.connectStream(c,m)},__pushEventStreamEvent(c){K&&(G==null||G.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!se||!K||Fr()},hideEventStream(){X&&pr()},isEventStreamVisible(){return X},showArtifacts(){cr(r)&&(kn=!1,Hn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(kn=!0,Hn())},upsertArtifact(c){return cr(r)?(kn=!1,j.upsertArtifact(c)):null},selectArtifact(c){cr(r)&&j.selectArtifact(c)},clearArtifacts(){cr(r)&&j.clearArtifacts()},getArtifacts(){var c;return(c=j==null?void 0:j.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=j==null?void 0:j.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!O&&!H()||!re?!1:(re.focus(),!0)},async resolveApproval(c,m,h){let T=j.getMessages().find(D=>{var z;return D.variant==="approval"&&((z=D.approval)==null?void 0:z.id)===c});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${c}`);if(T.approval.toolType==="webmcp"){j.resolveWebMcpApproval(T.id,m);return}return j.resolveApproval(T.approval,m,h)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(c){x(c)},on(c,m){return i.on(c,m)},off(c,m){i.off(c,m)},isOpen(){return F()&&O},isVoiceActive(){return ut.active},toggleReadAloud(c){j.toggleReadAloud(c)},stopReadAloud(){j.stopSpeaking()},getReadAloudState(c){return j.getReadAloudState(c)},onReadAloudChange(c){return j.onReadAloudChange(c)},getState(){return{open:F()&&O,launcherEnabled:L,voiceActive:ut.active,streaming:j.isStreaming()}},showCSATFeedback(c){!O&&F()&&qt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let h=Ki({onSubmit:async(b,T)=>{var D;j.isClientTokenMode()&&await j.submitCSATFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!O&&F()&&qt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let h=Gi({onSubmit:async(b,T)=>{var D;j.isClientTokenMode()&&await j.submitNPSFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return j.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return j.submitNPSFeedback(c,m)},destroy(){Fo!=null&&(clearInterval(Fo),Fo=null),gt.forEach(c=>c()),$e.remove(),Ve==null||Ve.remove(),en==null||en.destroy(),ln==null||ln.remove(),Mr&&S.removeEventListener("click",Mr)}};if((((Ud=n==null?void 0:n.debugTools)!=null?Ud:!1)||!!r.debug)&&typeof window!="undefined"){let c=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,gt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=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===c)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",m),gt.push(()=>{window.removeEventListener("persona:focusInput",m)}),se){let $=le=>{let ce=le.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&nn.showEventStream()},N=le=>{let ce=le.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===c)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",N),gt.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",N)})}let h=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&nn.showArtifacts()},b=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&nn.hideArtifacts()},T=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==c||N!=null&&N.artifact&&nn.upsertArtifact(N.artifact)},D=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==c||typeof(N==null?void 0:N.id)=="string"&&nn.selectArtifact(N.id)},z=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",z),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",z)})}let or=cx(r.persistState);if(or&&F()){let c=dx(or.storage),m=`${or.keyPrefix}widget-open`,h=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let T=((qd=or.persist)==null?void 0:qd.openState)&&c.getItem(m)==="true",D=((zd=or.persist)==null?void 0:zd.voiceState)&&c.getItem(h)==="true",z=((Vd=or.persist)==null?void 0:Vd.voiceState)&&c.getItem(b)==="true";if(T&&setTimeout(()=>{nn.open(),setTimeout(()=>{var $;if(D||z)nn.startVoiceRecognition();else if(($=or.persist)!=null&&$.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(Kd=or.persist)!=null&&Kd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(Gd=or.persist)!=null&&Gd.voiceState&&(i.on("voice:state",$=>{c.setItem(h,$.active?"true":"false")}),i.on("user:message",$=>{c.setItem(b,$.viaVoice?"true":"false")})),or.clearOnChatClear){let $=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},N=()=>$();window.addEventListener("persona:clear-chat",N),gt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return g&&F()&&setTimeout(()=>{nn.open()},0),fs(),Da||tm().then(()=>{j&&(cs++,Lr.clear(),Vs(rt,j.getMessages(),te))}).catch(()=>{}),nn};var px=(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},ux=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},mx=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gx=(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.")},ff=(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"},uc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},hf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",uc(e)},cc=e=>{e.style.transition=""},dc=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=""},pc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Qi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},fx=(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))},hx=(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)},yf=(e,t,n,r,o,s,a)=>{var v,x,M,E,P,L;let i=Qn(s),d=i.reveal==="push";fx(e,t,n,r,d),hx(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 l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(E=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?E:640,g=l!=null?l.innerWidth<=u:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),dc(t),cc(r),hf(r),pc(n),Qi(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((L=(P=s==null?void 0:s.launcher)==null?void 0:P.zIndex)!=null?L:Sn),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"),hf(r),ux(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",dc(t),cc(r),pc(n),Qi(o,r);let k=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=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=k,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",cc(r),uc(r),Qi(o,r);let k=px(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-k:0:a?0:-k;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+k}px`,t.style.transition=C,t.style.marginLeft=`${W}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="",dc(t),uc(r),pc(n),Qi(o,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!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",mx(r,i.maxHeight),r.style.overflow=k||W?"hidden":"visible",r.style.transition=C,k&&(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")}},yx=(e,t)=>{let n=e.ownerDocument.createElement("div");return ff(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){ff(n,r)},destroy(){n.remove()}}},bx=(e,t)=>{var L,k,I,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"),l=n.createElement("aside"),p=n.createElement("div"),u=(k=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||k?(C=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),Qn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{yf(a,i,d,l,p,t,u)}),g.observe(a))},x=!1,M=()=>{yf(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,gx(a,Qn(t)))},E=a.ownerDocument.defaultView,P=()=>{M()};return E==null||E.addEventListener("resize",P),Qn(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(W){let _=W.launcherEnabled?W.open:!0;u!==_&&(u=_,M())},updateConfig(W){var _,U;t=W,((U=(_=t==null?void 0:t.launcher)==null?void 0:_.enabled)!=null?U:!0)===!1&&(u=!0),M()},destroy(){E==null||E.removeEventListener("resize",P),f(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ha=(e,t)=>on(t)?bx(e,t):yx(e,t);var mc={},xx=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},vx=()=>{try{if(typeof mc!="undefined"&&mc.url)return new URL("../widget.css",mc.url).href}catch{}return null},bf=(e,t)=>{let n=vx(),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)}},gc=e=>{var M;let t=xx(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ha(t,o),a,i=[],d=(E,P)=>{var C,W;let k=!((W=(C=P==null?void 0:P.launcher)==null?void 0:C.enabled)!=null?W:!0)||on(P),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),k&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let _=E.attachShadow({mode:"open"});_.appendChild(I),bf(_,r)}else E.appendChild(I),bf(E,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let E=d(s.host,o);a=Xi(E,o,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),(M=e.onChatReady)==null||M.call(e);let f=E=>{g(),s.destroy(),s=Ha(t,E),o=E,u()},v={update(E){var W,_,U,H,F,O;let P={...o,...E,launcher:{...(W=o==null?void 0:o.launcher)!=null?W:{},...(_=E==null?void 0:E.launcher)!=null?_:{},dock:{...(H=(U=o==null?void 0:o.launcher)==null?void 0:U.dock)!=null?H:{},...(O=(F=E==null?void 0:E.launcher)==null?void 0:F.dock)!=null?O:{}}}},L=on(o),k=on(P),I=ko(o),C=ko(P);if(L!==k||I!==C){f(P);return}o=P,s.updateConfig(o),a.update(E),l()},destroy(){g(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(E,P,L){if(P==="host")return s.host;if(P in E)return Reflect.get(E,P,L);let k=a[P];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Af=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),wx=new Set(["button","a","input","select","textarea","details","summary"]),Cx=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),fc=/\b(product|card|item|listing|result)\b/i,yc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ax=3e3,Sx=100;function Sf(e){let t=typeof e.className=="string"?e.className:"";if(fc.test(t)||e.id&&fc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&fc.test(r.value))return!0}return!1}function Tf(e){var t;return yc.test(((t=e.textContent)!=null?t:"").trim())}function Ef(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 Tx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function xf(e){let t=e.match(yc);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 Ex(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 Mx="commerce-card",kx="result-card";function wf(e){return!Sf(e)||!Tf(e)||!Ef(e)&&!Tx(e)?0:5200}function Cf(e){var r;return!Sf(e)||Tf(e)||!Ef(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 bc=[{id:Mx,scoreElement(e){return wf(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||yc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(wf(e)===0)return null;let{title:n,href:r}=vf(e),o=(p=(l=xf(((d=e.textContent)!=null?d:"").trim()))!=null?l:xf(t.text))!=null?p:"",s=Ex(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(`
|
|
111
|
+
`}if(!b&&!c){let Ot="max-height: -moz-available !important; max-height: stretch !important;",Kt=m?"":"padding-top: 1.25em !important;",Ft=m?"":`z-index: ${(Ye=(Wr=r.launcher)==null?void 0:Wr.zIndex)!=null?Ye:Cn} !important;`;he.style.cssText+=Ot+Kt+Ft}Ge()};Tr(),To(e,r),_i(e,r),$i(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",lo)});let sn=null,an=null;gt.push(()=>{sn==null||sn(),sn=null,an==null||an(),an=null}),Nn&>.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),gt.push(()=>{Tn==null||Tn(),Tn=null,$r(),Wt&&(Wt.remove(),Wt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),oe&>.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),He==null||He.destroy(),He=null,K==null||K.destroy(),K=null,xe=null});let Er=null,Us=()=>{Er&&(Er(),Er=null),r.colorScheme==="auto"&&(Er=bi(()=>{To(e,r)}))};Us(),gt.push(()=>{Er&&(Er(),Er=null)}),gt.push(a);let jr=(Dd=r.features)==null?void 0:Dd.streamAnimation;if(jr!=null&&jr.type&&jr.type!=="none"){let c=wa(jr.type,jr.plugins);c&&(_l(c,e),gt.push(()=>Mg(e)))}let Bo=Vg(It),Mr=null,j,ls=c=>{var b,T;if(!j)return;let m=c!=null?c:j.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?Ya(m):null;h?Bo.render(h,j,te,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?Bo.render([],j,te,m):Bo.render(r.suggestionChips,j,te,m,r.suggestionChipsConfig)},kr=!1,Lr=fg(),Ur=new Map,Pr=new Map,pr=new Map,cs=0,Da=Vo()!==null,$n=wi(),jn=0,ur=null,mr=!1,Do=!1,qr=0,xn=null,Ir=null,ds=!1,No=!1,ps=null,Na=4,us=24,Oa=80,ms=new Map,ut={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},qs=(Od=(Nd=r.voiceRecognition)==null?void 0:Nd.autoResume)!=null?Od:!1,nr=c=>{i.emit("voice:state",{active:ut.active,source:c,timestamp:Date.now()})},Rn=()=>{x(c=>({...c,voiceState:{active:ut.active,timestamp:Date.now(),manuallyDeactivated:ut.manuallyDeactivated}}))},Fa=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=lc(p.voiceState),m=!!c.active,h=Number((T=c.timestamp)!=null?T:0);ut.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<ax&&setTimeout(()=>{var D,z;ut.active||(ut.manuallyDeactivated=!1,((z=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:z.type)==="runtype"?j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),nr("restore"),j.isVoiceActive()&&ys()}):$a("restore"))},1e3)},gs=()=>j?uf(j.getMessages()).filter(c=>!c.__skipPersist):[];function nt(c){if(!(l!=null&&l.save))return;let h={messages:c?uf(c):j?gs():[],metadata:p,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let b=l.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let w=null,V=()=>he.querySelector("#persona-scroll-container")||ke,q=()=>{w!==null&&(cancelAnimationFrame(w),w=null),mr=!1},J=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),Do=!1,q()},be=()=>{qr>0?(bn.textContent=String(qr),bn.style.display="",Ut.setAttribute("aria-label",`${yt()||"Jump to latest"} (${qr} new)`)):(bn.textContent="",bn.style.display="none",Ut.setAttribute("aria-label",yt()||"Jump to latest"))},$e=()=>{qr!==0&&(qr=0,be())},ft=()=>_t()==="follow"?!$n.isFollowing():!es(ke,us),at=()=>{if(!Yt()||G){Ut.parentNode&&Ut.remove(),Ut.style.display="none";return}Ut.parentNode!==Se&&Se.appendChild(Ut),Yn();let m=Yr(ke)>0&&ft();m||$e(),Ut.style.display=m?"":"none"},zs=()=>{$n.pause()&&(J(),at())},Wn=()=>{$n.resume(),$e(),at()},pn=(c=!1)=>{_t()==="follow"&&$n.isFollowing()&&(!c&&!kr||(ur!==null&&(cancelAnimationFrame(ur),ur=null),Do=!0,ur=requestAnimationFrame(()=>{ur=null,Do=!1,$n.isFollowing()&&Oo(V(),c?220:140)})))},un=(c,m,h,b=()=>!0)=>{let T=c.scrollTop,D=m(),z=D-T;q();let $=performance.now();mr=!0;let N=le=>1-Math.pow(1-le,3),ie=le=>{if(!b()){q();return}let Y=m();Y!==D&&(D=Y,z=D-T);let we=le-$,Fe=Math.min(we/h,1),Te=N(Fe),et=T+z*Te;c.scrollTop=et,jn=c.scrollTop,Fe<1?w=requestAnimationFrame(ie):(c.scrollTop=D,jn=c.scrollTop,w=null,mr=!1)};w=requestAnimationFrame(ie)},Oo=(c,m=500)=>{let h=Yr(c)-c.scrollTop;if(Math.abs(h)<1){jn=c.scrollTop;return}if(Math.abs(h)>=Oa){q(),mr=!0,c.scrollTop=Yr(c),jn=c.scrollTop,mr=!1;return}un(c,()=>Yr(c),m,()=>$n.isFollowing())},zr=()=>{let c=V();mr=!0,c.scrollTop=Yr(c),jn=c.scrollTop,mr=!1,at()},En=c=>{Ln.style.height=`${Math.max(0,Math.round(c))}px`,xn&&(xn.spacerHeight=Math.max(0,c))},hn=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),q(),xn=null,Ln.style.height="0px"},Un=c=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var ie;Ir=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=ke.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==ke;)b+=T.offsetTop,T=T.offsetParent;let D=(ie=xn==null?void 0:xn.spacerHeight)!=null?ie:0,z=ke.scrollHeight-D,{targetScrollTop:$,spacerHeight:N}=vg({anchorOffsetTop:b,topOffset:Bn(),viewportHeight:ke.clientHeight,contentHeight:z});xn={initialSpacerHeight:N,contentHeightAtAnchor:z,spacerHeight:N},En(N),un(ke,()=>$,220)})},Zf=()=>{if(_t()==="follow"){if(!$n.isFollowing()||es(ke,1))return;pn(!kr);return}if(xn&&xn.initialSpacerHeight>0){let c=ke.scrollHeight-xn.spacerHeight,m=wg({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:c});m!==xn.spacerHeight&&En(m)}at()},eh=c=>{let m=_t();m==="follow"?(Wn(),pn(!0)):m==="anchor-top"&&Un(c)},th=c=>{let m=new Map;c.forEach(h=>{let b=ms.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!No&&_t()!=="anchor-top"&&ft()&&(qr+=1,be(),at())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),ms.clear(),m.forEach((h,b)=>{ms.set(b,h)})},nh=(c,m,h)=>{var ot,Re,Pe,Ve,Ge,ht;let b=document.createElement("div"),D=(()=>{var De;let R=o.find(We=>We.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),z=(R,De)=>De==null?!1:typeof De=="string"?(R.textContent=De,!0):(R.appendChild(De),!0),$=new Set,N=new Set,ie=o.some(R=>R.renderAskUserQuestion),le=[],Y=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,Te=[];if(m.forEach(R=>{var Xe,Mt,rn,sr,zn,_o,$o,xs,vs,Xt,jo,go,fo,Kr,Uo,gr,Wr;$.add(R.id);let De=ie&&Gr(R),We=Fe&&R.variant==="approval"&&!!R.approval,me=!De&&R.role==="assistant"&&!R.variant&&we&&zi(R);if(!We&&pr.has(R.id)){let Ye=c.querySelector(`#wrapper-${R.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),pr.delete(R.id)}if(!me&&Pr.has(R.id)){let Ye=c.querySelector(`#wrapper-${R.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),Pr.delete(R.id)}let Nt=Gr(R)?`:${(Xe=R.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Mt=R.agentMetadata)!=null&&Mt.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ht=gg(R,cs)+Nt,Jt=De||We||me?null:hg(Lr,R.id,Ht);if(Jt){b.appendChild(Jt.cloneNode(!0)),Gr(R)&&((rn=R.toolCall)!=null&&rn.id)&&((sr=R.agentMetadata)==null?void 0:sr.awaitingLocalTool)===!0&&!((zn=R.agentMetadata)!=null&&zn.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ms(R,r,ze.composerOverlay));return}let bt=null,zt=o.find(Ye=>!!(R.variant==="reasoning"&&Ye.renderReasoning||R.variant==="tool"&&Ye.renderToolCall||!R.variant&&Ye.renderMessage)),qn=(_o=r.layout)==null?void 0:_o.messages;if(Gr(R)&&(($o=R.agentMetadata)==null?void 0:$o.askUserQuestionAnswered)===!0){Ur.delete(R.id);let Ye=c.querySelector(`#wrapper-${R.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime");return}if(la(R)&&((vs=(xs=r.features)==null?void 0:xs.suggestReplies)==null?void 0:vs.enabled)!==!1)return;if(Gr(R)&&((jo=(Xt=r.features)==null?void 0:Xt.askUserQuestion)==null?void 0:jo.enabled)!==!1){let Ye=o.find(Ot=>typeof Ot.renderAskUserQuestion=="function");if(Ye&&At.current){let Ot=Ur.get(R.id),Kt=Ot!==Ht,Ft=null;if(Kt){let{payload:$t,complete:mn}=Jr(R),Vn=R.id,Hr=()=>{var gn;return(gn=At.current)==null?void 0:gn.getMessages().find(fn=>fn.id===Vn)};Ft=Ye.renderAskUserQuestion({message:R,payload:$t,complete:mn,resolve:gn=>{var ar;let fn=Hr();fn&&((ar=At.current)==null||ar.resolveAskUserQuestion(fn,gn))},dismiss:()=>{var fn,ar,ho;let gn=Hr();(fn=gn==null?void 0:gn.agentMetadata)!=null&&fn.awaitingLocalTool&&((ar=At.current)==null||ar.markAskUserQuestionResolved(gn),(ho=At.current)==null||ho.resolveAskUserQuestion(gn,"(dismissed)"))},config:r})}let Qt=Ot!=null;if(Kt&&Ft===null&&!Qt){((go=R.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=R.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ms(R,r,ze.composerOverlay));return}let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${R.id}`,kt.setAttribute("data-wrapper-id",R.id),kt.setAttribute("data-ask-plugin-stub","true"),kt.setAttribute("data-preserve-runtime","true"),b.appendChild(kt),le.push({messageId:R.id,fingerprint:Ht,bubble:Ft});return}else{((Kr=R.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Uo=R.agentMetadata)!=null&&Uo.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Ms(R,r,ze.composerOverlay));return}}else if(We){let Ye=(gr=o.find(Qt=>typeof Qt.renderApproval=="function"))!=null?gr:s,Kt=pr.get(R.id)!==Ht,Ft=null;if(Kt&&(Ye!=null&&Ye.renderApproval)){let Qt=R.id,kt=($t,mn)=>{var Hr,gn,fn;let Vn=(Hr=At.current)==null?void 0:Hr.getMessages().find(ar=>ar.id===Qt);Vn!=null&&Vn.approval&&(Vn.approval.toolType==="webmcp"?(gn=At.current)==null||gn.resolveWebMcpApproval(Vn.id,$t):(fn=At.current)==null||fn.resolveApproval(Vn.approval,$t,mn))};Ft=Ye.renderApproval({message:R,defaultRenderer:()=>Oi(R,r),config:r,approve:$t=>kt("approved",$t),deny:$t=>kt("denied",$t)})}if(Kt&&Ft===null){let Qt=c.querySelector(`#wrapper-${R.id}`);Qt==null||Qt.removeAttribute("data-preserve-runtime"),pr.delete(R.id),bt=Oi(R,r)}else{let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${R.id}`,Qt.setAttribute("data-wrapper-id",R.id),Qt.setAttribute("data-approval-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),b.appendChild(Qt),Te.push({messageId:R.id,fingerprint:Ht,bubble:Ft});return}}else if(zt)if(R.variant==="reasoning"&&R.reasoning&&zt.renderReasoning){if(!Ae)return;bt=zt.renderReasoning({message:R,defaultRenderer:()=>Yl(R,r),config:r})}else if(R.variant==="tool"&&R.toolCall&&zt.renderToolCall){if(!Le)return;bt=zt.renderToolCall({message:R,defaultRenderer:()=>ec(R,r),config:r})}else zt.renderMessage&&(bt=zt.renderMessage({message:R,defaultRenderer:()=>{let Ye=Ns(R,h,qn,r.messageActions,fe,{loadingIndicatorRenderer:D,widgetConfig:r});return R.role!=="user"&&sc(Ye,R,r,j),Ye},config:r}));if(!bt&&me){let Ye=Vi(R);if(Ye){let Ot=Pr.get(R.id),Kt=Ot!==Ht,Ft=r.wrapComponentDirectiveInBubble!==!1,Qt=null;if(Kt){let kt=qi(Ye,{config:r,message:R,transform:h});if(kt)if(Ft){let $t=document.createElement("div");if($t.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(" "),$t.id=`bubble-${R.id}`,$t.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let mn=document.createElement("div");mn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",mn.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(mn)}$t.appendChild(kt),Qt=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${R.id}`,$t.setAttribute("data-message-id",R.id),$t.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let mn=document.createElement("div");mn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",mn.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(mn)}$t.appendChild(kt),Qt=$t}}if(Qt||Ot!=null){let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${R.id}`,kt.setAttribute("data-wrapper-id",R.id),kt.setAttribute("data-component-directive-stub","true"),kt.setAttribute("data-preserve-runtime","true"),Ft||kt.classList.add("persona-w-full"),b.appendChild(kt),Y.push({messageId:R.id,fingerprint:Ht,bubble:Qt});return}}}if(!bt)if(R.variant==="reasoning"&&R.reasoning){if(!Ae)return;bt=Yl(R,r)}else if(R.variant==="tool"&&R.toolCall){if(!Le)return;bt=ec(R,r)}else if(R.variant==="approval"&&R.approval){if(r.approval===!1)return;bt=Oi(R,r)}else{let Ye=(Wr=r.layout)==null?void 0:Wr.messages;Ye!=null&&Ye.renderUserMessage&&R.role==="user"?bt=Ye.renderUserMessage({message:R,config:r,streaming:!!R.streaming}):Ye!=null&&Ye.renderAssistantMessage&&R.role==="assistant"?bt=Ye.renderAssistantMessage({message:R,config:r,streaming:!!R.streaming}):bt=Ns(R,h,Ye,r.messageActions,fe,{loadingIndicatorRenderer:D,widgetConfig:r}),R.role!=="user"&&bt&&sc(bt,R,r,j)}let tn=document.createElement("div");tn.className="persona-flex",tn.id=`wrapper-${R.id}`,tn.setAttribute("data-wrapper-id",R.id),R.role==="user"&&tn.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&tn.classList.add("persona-w-full"),tn.appendChild(bt),yg(Lr,R.id,Ht,tn),b.appendChild(tn)}),ze.composerOverlay&&ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!N.has(We)&&vo(ze.composerOverlay,We)}),(Re=(ot=r.features)==null?void 0:ot.toolCallDisplay)!=null&&Re.grouped){let R=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Le){De.push(We);return}De.length>1&&R.push(De),De=[]}),De.length>1&&R.push(De),R.forEach((We,me)=>{var Xe,Mt;let Nt=We.map(rn=>Array.from(b.children).find(sr=>sr instanceof HTMLElement&&sr.getAttribute("data-wrapper-id")===rn.id)).filter(rn=>!!rn);if(Nt.length<2)return;let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-tool-group-${me}-${We[0].id}`,Ht.setAttribute("data-wrapper-id",`tool-group-${me}-${We[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 bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${We.length} tools`,qn=(Mt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Mt.call(Xe,{messages:We,toolCalls:We.map(rn=>rn.toolCall).filter(rn=>!!rn),defaultSummary:zt,config:r});z(bt,qn)||(bt.textContent=zt);let tn=document.createElement("div");tn.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(bt,tn),Ht.appendChild(Jt),Nt[0].before(Ht),Nt.forEach((rn,sr)=>{let zn=document.createElement("div");zn.className="persona-tool-group-item persona-relative",zn.setAttribute("data-persona-tool-group-item","true"),sr<Nt.length-1&&zn.setAttribute("data-persona-tool-group-connector","true"),zn.appendChild(rn),tn.appendChild(zn)})})}bg(Lr,$);let et=m.some(R=>R.role==="assistant"&&R.streaming),qe=m[m.length-1],dt=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(kr&&m.some(R=>R.role==="user")&&!et&&!dt){let R={config:r,streaming:!0,location:"standalone",defaultRenderer:ns},De=o.find(me=>me.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(R)),We===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(We=r.loadingIndicator.render(R)),We===null&&(We=ns()),We){let me=document.createElement("div"),Nt=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;me.className=Nt?["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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(We);let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id="wrapper-typing-indicator",Ht.setAttribute("data-wrapper-id","typing-indicator"),Ht.appendChild(me),b.appendChild(Ht)}}if(!kr&&m.length>0){let R=m[m.length-1],De={config:r,lastMessage:R,messageCount:m.length},We=o.find(Nt=>Nt.renderIdleIndicator),me=null;if(We!=null&&We.renderIdleIndicator&&(me=We.renderIdleIndicator(De)),me===null&&((Ge=r.loadingIndicator)!=null&&Ge.renderIdle)&&(me=r.loadingIndicator.renderIdle(De)),me){let Nt=document.createElement("div"),Ht=((ht=r.loadingIndicator)==null?void 0:ht.showBubble)!==!1;Nt.className=Ht?["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(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(me);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(Nt),b.appendChild(Jt)}}if(xi(c,b),le.length>0)for(let{messageId:R,fingerprint:De,bubble:We}of le){let me=c.querySelector(`#wrapper-${R}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),Ur.set(R,De))}if(Ur.size>0)for(let R of Ur.keys())$.has(R)||Ur.delete(R);if(Y.length>0)for(let{messageId:R,fingerprint:De,bubble:We}of Y){let me=c.querySelector(`#wrapper-${R}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),Pr.set(R,De))}if(Pr.size>0)for(let R of Pr.keys())$.has(R)||Pr.delete(R);if(Te.length>0)for(let{messageId:R,fingerprint:De,bubble:We}of Te){let me=c.querySelector(`#wrapper-${R}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),pr.set(R,De))}if(pr.size>0)for(let R of pr.keys())$.has(R)||pr.delete(R)},Vs=(c,m,h)=>{nh(c,m,h),ao()},Ks=null,rh=()=>{var h;if(Ks)return;let c=b=>{let T=b.composedPath();T.includes(he)||pt&&T.includes(pt)||qt(!1,"user")};Ks=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Ec=()=>{var m;if(!Ks)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Ks,!0),Ks=null};gt.push(()=>Ec());let Gs=null,oh=()=>{var h;if(Gs)return;let c=b=>{b.key==="Escape"&&(b.isComposing||qt(!1,"user"))};Gs=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Mc=()=>{var m;if(!Gs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Gs,!0),Gs=null};gt.push(()=>Mc());let Js=!1,kc=new Set,sh=()=>{var m,h,b,T;let c=(b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},fs=()=>{var dt,ot,Re,Pe;if(!H())return;let c=ze.peekBanner,m=ze.peekTextNode;if(!c||!m)return;if(O){c.classList.remove("persona-pill-peek--visible");return}let h=(dt=j==null?void 0:j.getMessages())!=null?dt:[],b;for(let Ve=h.length-1;Ve>=0;Ve--){let Ge=h[Ve];if(Ge.role==="assistant"&&Ge.content){b=Ge;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let T=b.content,D=!!b.streaming,z=sh(),$=Si(z),N=$.type!=="none"?wa($.type,z==null?void 0:z.plugins):null,ie=((ot=N==null?void 0:N.isAnimating)==null?void 0:ot.call(N,b))===!0,le=N!==null&&(D||ie);le&&N&&!kc.has(N.name)&&(_l(N,e),kc.add(N.name));let Y=le&&(N!=null&&N.containerClass)?N.containerClass:null,we=(Re=m.dataset.personaPeekStreamClass)!=null?Re:null;we&&we!==Y&&(m.classList.remove(we),delete m.dataset.personaPeekStreamClass),Y&&we!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),le?(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=le?Ti(T,$.buffer,N,b,D):T;if(le&&$.placeholder==="skeleton"&&D&&(!Fe||!Fe.trim())){let Ve=document.createElement("div"),Ge=Aa();Ge.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Ge),xi(m,Ve)}else{let Ve=Math.max(0,Fe.length-100),Ge=Fe.length>100?Fe.slice(-100):Fe,ht=Br(Ge);if(!le||!N){let R=Fe.length>100?`\u2026${Ge}`:Ge;m.textContent!==R&&(m.textContent=R)}else{let R=ht;(N.wrap==="char"||N.wrap==="word")&&(R=Ca(ht,N.wrap,`peek-${b.id}`,{skipTags:N.skipTags,startIndex:Ve}));let De=document.createElement("div");if(De.innerHTML=R,N.useCaret&&Ge.length>0){let We=Ei(),me=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=me[me.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(We,Nt.nextSibling):De.appendChild(We)}xi(m,De),(Pe=N.onAfterRender)==null||Pe.call(N,{container:m,bubble:c,messageId:b.id,message:b,speed:$.speed,duration:$.duration})}}let qe=kr||Js;c.classList.toggle("persona-pill-peek--visible",qe)};if(H()){let c=ze.peekBanner;if(c){let b=T=>{T.preventDefault(),T.stopPropagation(),qt(!0,"user")};c.addEventListener("pointerdown",b),gt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Js||(Js=!0,fs())},h=()=>{Js&&(Js=!1,fs())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",h),gt.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",h)}),pt&&(pt.addEventListener("pointerenter",m),pt.addEventListener("pointerleave",h),gt.push(()=>{pt.removeEventListener("pointerenter",m),pt.removeEventListener("pointerleave",h)}))}let ah=c=>{var we,Fe,Te,et,qe,dt,ot,Re;let m=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(Te=m.expandedSize)!=null?Te:"anchored",b=(et=m.bottomOffset)!=null?et:"16px",T=m.collapsedMaxWidth,D=(qe=m.expandedMaxWidth)!=null?qe:"880px",z=(dt=m.expandedTopOffset)!=null?dt:"5vh",$=(ot=m.modalMaxWidth)!=null?ot:"880px",N=(Re=m.modalMaxHeight)!=null?Re:"min(90vh, 800px)",ie="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",Y=he.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",pt){let Pe=pt.style;Pe.bottom=b,Pe.width=T!=null?T:""}if(c&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=$,Y.maxWidth=ie,Y.maxHeight=N,Y.height=N;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${le})`,Y.top=z,Y.width=D,Y.maxWidth=ie}},Xs=()=>{var N,ie,le,Y,we,Fe,Te,et;if(!F())return;if(H()){let dt=(le=((ie=(N=r.launcher)==null?void 0:N.composerBar)!=null?ie:{}).expandedSize)!=null?le:"anchored",ot=O?"expanded":"collapsed";he.dataset.state=ot,he.dataset.expandedSize=dt,pt&&(pt.dataset.state=ot,pt.dataset.expandedSize=dt),he.style.removeProperty("display"),he.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ah(O),Se.style.display=O?"flex":"none",Tr(),O?(rh(),oh()):(Ec(),Mc()),fs();return}let c=on(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(et=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?et:!0,T=m.innerWidth<=h,D=b&&T&&L,z=Jn(r).reveal;O?(he.style.removeProperty("display"),he.style.display=c?"flex":"",he.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),en?en.element.style.display="none":ln&&(ln.style.display="none")):(c?c&&(z==="overlay"||z==="push")&&!D?(he.style.removeProperty("display"),he.style.display="flex",he.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(he.style.setProperty("display","none","important"),he.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(he.style.display="",he.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),en?en.element.style.display=c?"none":"":ln&&(ln.style.display=c?"none":""))},qt=(c,m="user")=>{var D,z;if(!F()||O===c)return;let h=O;O=c,Xs();let b=(()=>{var Te,et,qe,dt,ot,Re,Pe,Ve,Ge,ht;let $=(et=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?et:!1,N=(qe=e.ownerDocument.defaultView)!=null?qe:window,ie=(ot=(dt=r.launcher)==null?void 0:dt.mobileFullscreen)!=null?ot:!0,le=(Pe=(Re=r.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Pe:640,Y=N.innerWidth<=le,we=on(r)&&ie&&Y,Fe=H()&&((ht=(Ge=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:Ge.expandedSize)!=null?ht:"fullscreen")==="fullscreen";return $||ie&&Y&&L||we||Fe})();if(O&&b){if(!sn){let $=e.getRootNode(),N=$ instanceof ShadowRoot?$.host:e.closest(".persona-host");N&&(sn=$l(N,(z=(D=r.launcher)==null?void 0:D.zIndex)!=null?z:Cn))}an||(an=jl(e.ownerDocument))}else O||(sn==null||sn(),sn=null,an==null||an(),an=null);O&&(Qs(),_t()==="follow"?pn(!0):zr());let T={open:O,source:m,timestamp:Date.now()};O&&!h?i.emit("widget:opened",T):!O&&h&&i.emit("widget:closed",T),i.emit("widget:state",{open:O,launcherEnabled:L,voiceActive:ut.active,streaming:j.isStreaming()})},ol=c=>{de(c?"stop":"send"),B&&(B.disabled=c),Bo.buttons.forEach(m=>{m.disabled=c}),Oe.dataset.personaComposerStreaming=c?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},sl=()=>{ut.active||te&&te.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>sl(),200)});let Lc=()=>{var h,b,T,D,z,$,N,ie,le,Y,we;vr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",wr.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",te.placeholder=($=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?$:"How can I help...";let c=ke.querySelector("[data-persona-intro-card]");if(c){let Fe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;c.style.display=Fe?"":"none",Fe?(ke.classList.remove("persona-gap-3"),ke.classList.add("persona-gap-6")):(ke.classList.remove("persona-gap-6"),ke.classList.add("persona-gap-3"))}!((le=(ie=r.sendButton)==null?void 0:ie.useIcon)!=null&&le)&&!(j!=null&&j.isStreaming())&&(Ue.textContent=(we=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?we:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=p.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{x(m=>({...m,sessionId:c}))}});let Fo=null,ih=()=>{Fo==null&&(Fo=setInterval(()=>{let c=rt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Fo),Fo=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=ei(m-b))})},100))};j=new Is(r,{onMessagesChanged(c){var b;Vs(rt,c,ee),ih(),ls(c),pn(!kr),th(c);let m=[...c].reverse().find(T=>T.role==="user");c.length===0&&hn(),!ds||No?(ds=!0,ps=(b=m==null?void 0:m.id)!=null?b:null):m&&m.id!==ps&&(ps=m.id,eh(m.id));let h=ut.lastUserMessageId;m&&m.id!==h&&(ut.lastUserMessageId=m.id,i.emit("user:message",m)),ut.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),nt(c),fs()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};jt(yn,(T=>{var D,z,$,N;return T==="idle"?(D=m.idleText)!=null?D:wn.idle:T==="connecting"?(z=m.connectingText)!=null?z:wn.connecting:T==="connected"?($=m.connectedText)!=null?$:wn.connected:T==="error"?(N=m.errorText)!=null?N:wn.error:wn[T]})(c),m,c)},onStreamingChanged(c){kr=c,ol(c),j&&Vs(rt,j.getMessages(),ee),c||pn(!0),fs()},onVoiceStatusChanged(c){var m,h;if(i.emit("voice:status",{status:c,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":Vr(),ys();break;case"processing":Vr(),uh();break;case"speaking":Vr(),mh();break;default:c==="idle"&&j.isBargeInActive()?(Vr(),ys(),B==null||B.setAttribute("aria-label","End voice session")):(ut.active=!1,Vr(),nr("system"),Rn());break}},onArtifactsState(c){On=c,In(),nt()}}),At.current=j;let al=null;if(j.onReadAloudChange((c,m)=>{var T;oo=c,so=m,ao();let h=c!=null?c:al;c&&(al=c);let b=h&&(T=j.getMessages().find(D=>D.id===h))!=null?T:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(al=null)}),ds=!0,((_d=(Fd=r.voiceRecognition)==null?void 0:Fd.provider)==null?void 0:_d.type)==="runtype")try{j.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&j.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||r.onSSEEvent)&&j.setSSEEventCallback((c,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,c,m),Q==null||Q.processEvent(c,m),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(c=>{var m,h,b;if(c){if(c.metadata&&(p=lc(c.metadata),P.syncFromMetadata()),(m=c.messages)!=null&&m.length){No=!0;try{j.hydrateMessages(c.messages)}finally{No=!1}}(h=c.artifacts)!=null&&h.length&&j.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Pc=()=>{var m,h,b;!H()||O||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||qt(!0,"auto")},Ic=c=>{var T;if(c.preventDefault(),j.isStreaming()){j.cancel(),Q==null||Q.reset(),He==null||He.update();return}let m=te.value.trim(),h=(T=Ct==null?void 0:Ct.hasAttachments())!=null?T:!1;if(!m&&!h)return;Pc();let b;h&&(b=[],b.push(...Ct.getContentParts()),m&&b.push(ma(m))),te.value="",te.style.height="auto",_a(),j.sendMessage(m,{contentParts:b}),h&&Ct.clearAttachments()},lh=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},il={...vi},ll=!1,_a=()=>{il={...vi}},ch=()=>j.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),dh=c=>{if(!te)return;ll=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),ll=!1;let m=te.value.length;te.setSelectionRange(m,m)},Rc=()=>{ll||_a()},Wc=c=>{if(te){if(lh()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=te.selectionStart===0&&te.selectionEnd===0,h=mg({direction:c.key==="ArrowUp"?"up":"down",history:ch(),currentValue:te.value,atStart:m,state:il});if(il=h.state,h.handled){c.preventDefault(),h.value!==void 0&&dh(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(j.isStreaming()){c.preventDefault();return}_a(),c.preventDefault(),Ue.click()}}},Hc=c=>{c.key!=="Escape"||c.isComposing||j.isStreaming()&&c.composedPath().includes(Se)&&(j.cancel(),Q==null||Q.reset(),He==null||He.update(),_a(),c.preventDefault(),c.stopImmediatePropagation())},Bc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Ct)return;let m=lx(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ct.handleFiles(m))},rr=null,Rr=!1,hs=null,ct=null,Dc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$a=(c="user")=>{var D,z,$,N,ie,le,Y;if(Rr||j.isStreaming())return;let m=Dc();if(!m)return;rr=new m;let b=(z=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?z:2e3;rr.continuous=!0,rr.interimResults=!0,rr.lang="en-US";let T=te.value;rr.onresult=we=>{let Fe="",Te="";for(let qe=0;qe<we.results.length;qe++){let dt=we.results[qe],ot=dt[0].transcript;dt.isFinal?Fe+=ot+" ":Te=ot}let et=T+Fe+Te;te.value=et,hs&&clearTimeout(hs),(Fe||Te)&&(hs=window.setTimeout(()=>{let qe=te.value.trim();qe&&rr&&Rr&&(uo(),te.value="",te.style.height="auto",j.sendMessage(qe,{viaVoice:!0}))},b))},rr.onerror=we=>{we.error!=="no-speech"&&uo()},rr.onend=()=>{if(Rr){let we=te.value.trim();we&&we!==T.trim()&&(te.value="",te.style.height="auto",j.sendMessage(we,{viaVoice:!0})),uo()}};try{if(rr.start(),Rr=!0,ut.active=!0,c!=="system"&&(ut.manuallyDeactivated=!1),nr(c),Rn(),B){let we=($=r.voiceRecognition)!=null?$:{};ct={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(N=we.iconName)!=null?N:"mic",iconSize:parseFloat((Y=(le=we.iconSize)!=null?le:(ie=r.sendButton)==null?void 0:ie.size)!=null?Y:"40")||24};let Fe=we.recordingBackgroundColor,Te=we.recordingIconColor,et=we.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let qe=B.querySelector("svg");qe&&qe.setAttribute("stroke",Te)}et&&(B.style.borderColor=et),B.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(c="user")=>{if(Rr){if(Rr=!1,hs&&(clearTimeout(hs),hs=null),rr){try{rr.stop()}catch{}rr=null}if(ut.active=!1,nr(c),Rn(),B){if(B.classList.remove("persona-voice-recording"),ct){B.style.backgroundColor=ct.backgroundColor,B.style.color=ct.color,B.style.borderColor=ct.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",ct.color||"currentColor"),ct=null}B.setAttribute("aria-label","Start voice recognition")}}},ph=(c,m)=>{var ot,Re,Pe,Ve,Ge,ht,R,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ot=c==null?void 0:c.provider)==null?void 0:ot.type)==="runtype",T=((Re=c==null?void 0:c.provider)==null?void 0:Re.type)==="custom";if(!(h||b||T))return null;let z=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=(Pe=c==null?void 0:c.iconName)!=null?Pe:"mic",ie=(Ve=m==null?void 0:m.size)!=null?Ve:"40px",le=(Ge=c==null?void 0:c.iconSize)!=null?Ge:ie,Y=parseFloat(le)||24,we=(ht=c==null?void 0:c.backgroundColor)!=null?ht:m==null?void 0:m.backgroundColor,Fe=(R=c==null?void 0:c.iconColor)!=null?R:m==null?void 0:m.textColor;$.style.width=le,$.style.height=le,$.style.minWidth=le,$.style.minHeight=le,$.style.fontSize="18px",$.style.lineHeight="1",Fe?$.style.color=Fe:$.style.color="var(--persona-text, #111827)";let et=ge(N,Y,Fe||"currentColor",1.5);et?$.appendChild(et):$.textContent="\u{1F3A4}",we?$.style.backgroundColor=we:$.style.backgroundColor="",c!=null&&c.borderWidth&&($.style.borderWidth=c.borderWidth,$.style.borderStyle="solid"),c!=null&&c.borderColor&&($.style.borderColor=c.borderColor),c!=null&&c.paddingX&&($.style.paddingLeft=c.paddingX,$.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&($.style.paddingTop=c.paddingY,$.style.paddingBottom=c.paddingY),z.appendChild($);let qe=(De=c==null?void 0:c.tooltipText)!=null?De:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&qe){let me=y("div","persona-send-button-tooltip");me.textContent=qe,z.appendChild(me)}return{micButton:$,micButtonWrapper:z}},cl=()=>{var m,h,b,T,D;if(!B||ct)return;let c=(m=r.voiceRecognition)!=null?m:{};ct={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((D=(T=c.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},dl=(c,m)=>{var D,z,$,N,ie;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let b=(ie=ct==null?void 0:ct.iconSize)!=null?ie:parseFloat((N=($=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?$:(z=r.sendButton)==null?void 0:z.size)!=null?N:"40")||24,T=ge(c,b,m,1.5);T&&B.appendChild(T)},ja=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ys=()=>{var T;if(!B)return;cl();let c=(T=r.voiceRecognition)!=null?T:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(ja(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=B.querySelector("svg");D&&D.setAttribute("stroke",h)}b&&(B.style.borderColor=b),B.setAttribute("aria-label","Stop voice recognition")},uh=()=>{var $,N,ie,le,Y,we,Fe,Te;if(!B)return;cl();let c=($=r.voiceRecognition)!=null?$:{},m=j.getVoiceInterruptionMode(),h=(N=c.processingIconName)!=null?N:"loader",b=(le=(ie=c.processingIconColor)!=null?ie:ct==null?void 0:ct.color)!=null?le:"",T=(we=(Y=c.processingBackgroundColor)!=null?Y:ct==null?void 0:ct.backgroundColor)!=null?we:"",D=(Te=(Fe=c.processingBorderColor)!=null?Fe:ct==null?void 0:ct.borderColor)!=null?Te:"";ja(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=T,B.style.borderColor=D;let z=b||"currentColor";B.style.color=z,dl(h,z),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},mh=()=>{var ie,le,Y,we,Fe,Te,et,qe,dt,ot,Re,Pe;if(!B)return;cl();let c=(ie=r.voiceRecognition)!=null?ie:{},m=j.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:h,T=(Te=c.speakingIconColor)!=null?Te:m==="barge-in"?(we=(Y=c.recordingIconColor)!=null?Y:ct==null?void 0:ct.color)!=null?we:"":(Fe=ct==null?void 0:ct.color)!=null?Fe:"",D=(dt=c.speakingBackgroundColor)!=null?dt:m==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(qe=ct==null?void 0:ct.backgroundColor)!=null?qe:"",z=(Pe=c.speakingBorderColor)!=null?Pe:m==="barge-in"?(ot=c.recordingBorderColor)!=null?ot:"":(Re=ct==null?void 0:ct.borderColor)!=null?Re:"";ja(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=D,B.style.borderColor=z;let $=T||"currentColor";B.style.color=$,dl(b,$);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",N),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},Vr=()=>{var c,m,h;B&&(ja(),ct&&(B.style.backgroundColor=(c=ct.backgroundColor)!=null?c:"",B.style.color=(m=ct.color)!=null?m:"",B.style.borderColor=(h=ct.borderColor)!=null?h:"",dl(ct.iconName,ct.color||"currentColor"),ct=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ua=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let h=j.getVoiceStatus(),b=j.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){j.stopVoicePlayback();return}if(j.isBargeInActive()){j.stopVoicePlayback(),j.deactivateBargeIn().then(()=>{ut.active=!1,ut.manuallyDeactivated=!0,Rn(),nr("user"),Vr()});return}j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),ut.manuallyDeactivated=!j.isVoiceActive(),Rn(),nr("user"),j.isVoiceActive()?ys():Vr()});return}if(Rr){let h=te.value.trim();ut.manuallyDeactivated=!0,Rn(),uo("user"),h&&(te.value="",te.style.height="auto",j.sendMessage(h))}else ut.manuallyDeactivated=!1,Rn(),$a("user")};Cr=Ua,B&&(B.addEventListener("click",Ua),gt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(j.isVoiceActive()&&j.toggleVoice(),Vr()):uo("system"),B&&B.removeEventListener("click",Ua)}));let gh=i.on("assistant:complete",()=>{qs&&(ut.active||ut.manuallyDeactivated||qs==="assistant"&&!ut.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!ut.active&&!ut.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),nr("auto"),j.isVoiceActive()&&ys()}):$a("auto"))},600))});gt.push(gh);let fh=i.on("action:resubmit",()=>{setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)});gt.push(fh);let Nc=()=>{qt(!O,"user")},en=null,ln=null;if(L&&!H()){let{instance:c,element:m}=Kl({config:r,plugins:o,onToggle:Nc});en=c,c||(ln=m)}en?e.appendChild(en.element):ln&&e.appendChild(ln),Xs(),ls(),Lc(),ol(j.isStreaming()),_t()==="follow"?pn(!0):zr(),Fa(),I&&(!L||H()?setTimeout(()=>sl(),0):O&&setTimeout(()=>sl(),200));let Qs=()=>{var N,ie,le,Y,we,Fe,Te,et,qe,dt,ot,Re,Pe,Ve,Ge,ht,R,De,We,me,Nt,Ht;if(H()){Yn(),Xs();return}let c=on(r),m=(ie=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?ie:!1,h=c||m||((Y=(le=r.launcher)==null?void 0:le.fullHeight)!=null?Y:!1),b=(we=e.ownerDocument.defaultView)!=null?we:window,T=(Te=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Te:!0,D=(qe=(et=r.launcher)==null?void 0:et.mobileBreakpoint)!=null?qe:640,z=b.innerWidth<=D,$=T&&z&&L;try{if($){Tr(),To(e,r);return}if(U&&(U=!1,Tr(),To(e,r)),!L&&!c){X.style.height="",X.style.width="";return}if(!m&&!c){let Jt=(ot=(dt=r==null?void 0:r.launcher)==null?void 0:dt.width)!=null?ot:r==null?void 0:r.launcherWidth,bt=Jt!=null?Jt:Gn;X.style.width=bt,X.style.maxWidth=bt}if(ve(),!h){let Jt=b.innerHeight,bt=64,zt=(Pe=(Re=r.launcher)==null?void 0:Re.heightOffset)!=null?Pe:0,qn=Math.max(200,Jt-bt),tn=Math.min(640,qn),Xe=Math.max(200,tn-zt);X.style.height=`${Xe}px`}}finally{if(Yn(),Xs(),O&&L){let bt=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((ht=(Ge=r.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?ht:640),zt=(De=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?De:!1,qn=(me=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?me:!0,tn=on(r)&&qn&&bt,Xe=zt||qn&&bt&&L||tn;if(Xe&&!an){let Mt=e.getRootNode(),rn=Mt instanceof ShadowRoot?Mt.host:e.closest(".persona-host");rn&&!sn&&(sn=$l(rn,(Ht=(Nt=r.launcher)==null?void 0:Nt.zIndex)!=null?Ht:Cn)),an=jl(e.ownerDocument)}else Xe||(sn==null||sn(),sn=null,an==null||an(),an=null)}}};Qs();let Oc=($d=e.ownerDocument.defaultView)!=null?$d:window;if(Oc.addEventListener("resize",Qs),gt.push(()=>Oc.removeEventListener("resize",Qs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Yn()});c.observe(Oe),gt.push(()=>c.disconnect())}jn=ke.scrollTop;let Fc=Yr(ke),hh=()=>{let c=ke.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:ke.ownerDocument.getSelection()},pl=()=>xg(hh(),ke),_c=()=>{let c=ke.scrollTop,m=Yr(ke),h=m<Fc;if(Fc=m,_t()!=="follow"){jn=c,at();return}let{action:b,nextLastScrollTop:T}=Ci({following:$n.isFollowing(),currentScrollTop:c,lastScrollTop:jn,nearBottom:es(ke,us),userScrollThreshold:Na,isAutoScrolling:mr||Do||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(jn=T,b==="resume"){pl()||Wn();return}b==="pause"&&zs()};if(ke.addEventListener("scroll",_c,{passive:!0}),gt.push(()=>ke.removeEventListener("scroll",_c)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Zf()});c.observe(rt),c.observe(ke),gt.push(()=>c.disconnect())}let $c=()=>{_t()==="follow"&&$n.isFollowing()&&pl()&&zs()},jc=ke.ownerDocument;jc.addEventListener("selectionchange",$c),gt.push(()=>{jc.removeEventListener("selectionchange",$c)});let Uc=c=>{if(_t()!=="follow")return;let m=Ai({following:$n.isFollowing(),deltaY:c.deltaY,nearBottom:es(ke,us),resumeWhenNearBottom:!0});m==="pause"?zs():m==="resume"&&!pl()&&Wn()};ke.addEventListener("wheel",Uc,{passive:!0}),gt.push(()=>ke.removeEventListener("wheel",Uc)),Ut.addEventListener("click",()=>{hn(),ke.scrollTop=ke.scrollHeight,jn=ke.scrollTop,Wn(),pn(!0),at()}),gt.push(()=>Ut.remove()),gt.push(()=>{J(),hn()});let qc=()=>{S&&(Mr&&(S.removeEventListener("click",Mr),Mr=null),F()?(S.style.display="",Mr=()=>{qt(!1,"user")},S.addEventListener("click",Mr)):S.style.display="none")};qc(),(()=>{let{clearChatButton:c}=ze;c&&c.addEventListener("click",()=>{j.clearMessages(),Lr.clear(),Wn(),vo(ze.composerOverlay);try{localStorage.removeItem(js),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${js}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==js)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),l!=null&&l.clear)try{let h=l.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},P.syncFromMetadata(),K==null||K.clear(),Q==null||Q.reset(),He==null||He.update()})})(),vt&&vt.addEventListener("submit",Ic),te==null||te.addEventListener("keydown",Wc),te==null||te.addEventListener("input",Rc),te==null||te.addEventListener("paste",Bc);let zc=(jd=e.ownerDocument)!=null?jd:document;zc.addEventListener("keydown",Hc,!0);let Vc="persona-attachment-drop-active",Ys=0,ul=()=>{Ys=0,Se.classList.remove(Vc)},bs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},Kc=c=>{!Ji(c.dataTransfer)||!bs()||(Ys++,Ys===1&&Se.classList.add(Vc))},Gc=c=>{!Ji(c.dataTransfer)||!bs()||(Ys--,Ys<=0&&ul())},Jc=c=>{!Ji(c.dataTransfer)||!bs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Xc=c=>{var h;if(!Ji(c.dataTransfer)||!bs())return;c.preventDefault(),c.stopPropagation(),ul();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&Ct.handleFiles(m)},mo=!0;Se.addEventListener("dragenter",Kc,mo),Se.addEventListener("dragleave",Gc,mo),e.addEventListener("dragover",Jc,mo),e.addEventListener("drop",Xc,mo);let qa=e.ownerDocument,Qc=c=>{bs()&&c.preventDefault()},Yc=c=>{bs()&&c.preventDefault()};qa.addEventListener("dragover",Qc),qa.addEventListener("drop",Yc),gt.push(()=>{vt&&vt.removeEventListener("submit",Ic),te==null||te.removeEventListener("keydown",Wc),te==null||te.removeEventListener("input",Rc),te==null||te.removeEventListener("paste",Bc),zc.removeEventListener("keydown",Hc,!0)}),gt.push(()=>{Se.removeEventListener("dragenter",Kc,mo),Se.removeEventListener("dragleave",Gc,mo),e.removeEventListener("dragover",Jc,mo),e.removeEventListener("drop",Xc,mo),qa.removeEventListener("dragover",Qc),qa.removeEventListener("drop",Yc),ul()}),gt.push(()=>{j.cancel()}),en?gt.push(()=>{en==null||en.destroy()}):ln&>.push(()=>{ln==null||ln.remove()});let nn={update(c){var $t,mn,Vn,Hr,gn,fn,ar,ho,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,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;let m=r.toolCall,h=r.messageActions,b=($t=r.layout)==null?void 0:$t.messages,T=r.colorScheme,D=r.loadingIndicator,z=r.iterationDisplay,$=(mn=r.features)==null?void 0:mn.showReasoning,N=(Vn=r.features)==null?void 0:Vn.showToolCalls,ie=(Hr=r.features)==null?void 0:Hr.toolCallDisplay,le=(gn=r.features)==null?void 0:gn.reasoningDisplay;r={...r,...c},Tr(),To(e,r),_i(e,r),$i(e,r),In(),r.colorScheme!==T&&Us();let Y=Ia.getForInstance(r.plugins);o.length=0,o.push(...Y),L=(ar=(fn=r.launcher)==null?void 0:fn.enabled)!=null?ar:!0,k=(Jd=(ho=r.launcher)==null?void 0:ho.autoExpand)!=null?Jd:!1,Ae=(Qd=(Xd=r.features)==null?void 0:Xd.showReasoning)!=null?Qd:!0,Le=(Zd=(Yd=r.features)==null?void 0:Yd.showToolCalls)!=null?Zd:!0,Ce=(tp=(ep=r.features)==null?void 0:ep.scrollToBottom)!=null?tp:{};let we=_t();ce=(rp=(np=r.features)==null?void 0:np.scrollBehavior)!=null?rp:{},we!==_t()&&(hn(),Wn()),no(),at();let Fe=oe;if(oe=(sp=(op=r.features)==null?void 0:op.showEventStreamToggle)!=null?sp:!1,oe&&!Fe){if(K||(xe=new La(se),K=new ka(Be,xe),Q=Q!=null?Q:new Pa,xe.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),j.setSSEEventCallback((re,St)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,re,St),Q==null||Q.processEvent(re,St),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(St)})})),!mt&&Ie){let re=(ip=(ap=r.features)==null?void 0:ap.eventStream)==null?void 0:ip.classNames,St="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");mt=y("button",St),mt.style.width="28px",mt.style.height="28px",mt.style.color=kn.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Vt=ge("activity","18px","currentColor",1.5);Vt&&mt.appendChild(Vt);let st=ze.clearChatButtonWrapper,Lt=ze.closeButtonWrapper,cn=st||Lt;cn&&cn.parentNode===Ie?Ie.insertBefore(mt,cn):Ie.appendChild(mt),mt.addEventListener("click",()=>{G?dr():Or()})}}else!oe&&Fe&&(dr(),mt&&(mt.remove(),mt=null),K==null||K.clear(),xe==null||xe.destroy(),K=null,xe=null,Q==null||Q.reset(),Q=null);if(((lp=r.launcher)==null?void 0:lp.enabled)===!1&&en&&(en.destroy(),en=null),((cp=r.launcher)==null?void 0:cp.enabled)===!1&&ln&&(ln.remove(),ln=null),((dp=r.launcher)==null?void 0:dp.enabled)!==!1&&!en&&!ln){let{instance:re,element:St}=Kl({config:r,plugins:o,onToggle:Nc});en=re,re||(ln=St),e.appendChild(St)}en&&en.update(r),Ee&&((pp=r.launcher)==null?void 0:pp.title)!==void 0&&(Ee.textContent=r.launcher.title),Ne&&((up=r.launcher)==null?void 0:up.subtitle)!==void 0&&(Ne.textContent=r.launcher.subtitle);let Te=(mp=r.layout)==null?void 0:mp.header;if((Te==null?void 0:Te.layout)!==_&&Ie){let re=Te?Bs(r,Te,{showClose:F(),onClose:()=>qt(!1,"user")}):Zr({config:r,showClose:F(),onClose:()=>qt(!1,"user")});Qe.replaceHeader(re),Ie=Qe.header.element,ne=Qe.header.iconHolder,Ee=Qe.header.headerTitle,Ne=Qe.header.headerSubtitle,S=Qe.header.closeButton,_=Te==null?void 0:Te.layout}else if(Te&&(ne&&(ne.style.display=Te.showIcon===!1?"none":""),Ee&&(Ee.style.display=Te.showTitle===!1?"none":""),Ne&&(Ne.style.display=Te.showSubtitle===!1?"none":""),S&&(S.style.display=Te.showCloseButton===!1?"none":""),ze.clearChatButtonWrapper)){let re=Te.showClearChat;if(re!==void 0){ze.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:St}=ze;St&&!St.classList.contains("persona-absolute")&&(re?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let qe=((gp=r.layout)==null?void 0:gp.showHeader)!==!1;Ie&&(Ie.style.display=qe?"":"none");let dt=((fp=r.layout)==null?void 0:fp.showFooter)!==!1;Oe&&(Oe.style.display=dt?"":"none"),Yn(),at(),L!==W?L?qt(k,"auto"):(O=!0,Xs()):k!==C&&qt(k,"auto"),C=k,W=L,Qs(),qc();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(m),Ve=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((hp=r.layout)==null?void 0:hp.messages)!==JSON.stringify(b),ht=((yp=r.loadingIndicator)==null?void 0:yp.render)!==(D==null?void 0:D.render)||((bp=r.loadingIndicator)==null?void 0:bp.renderIdle)!==(D==null?void 0:D.renderIdle)||((xp=r.loadingIndicator)==null?void 0:xp.showBubble)!==(D==null?void 0:D.showBubble),R=r.iterationDisplay!==z,De=((wp=(vp=r.features)==null?void 0:vp.showReasoning)!=null?wp:!0)!==($!=null?$:!0)||((Ap=(Cp=r.features)==null?void 0:Cp.showToolCalls)!=null?Ap:!0)!==(N!=null?N:!0)||JSON.stringify((Sp=r.features)==null?void 0:Sp.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((Tp=r.features)==null?void 0:Tp.reasoningDisplay)!==JSON.stringify(le);(Pe||Ve||Ge||ht||R||De)&&j&&(cs++,Vs(rt,j.getMessages(),ee));let me=(Ep=r.launcher)!=null?Ep:{},Nt=(Mp=me.headerIconHidden)!=null?Mp:!1,Ht=(Lp=(kp=r.layout)==null?void 0:kp.header)==null?void 0:Lp.showIcon,Jt=Nt||Ht===!1,bt=me.headerIconName,zt=(Pp=me.headerIconSize)!=null?Pp:"48px";if(ne){let re=Se.querySelector(".persona-border-b-persona-divider"),St=re==null?void 0:re.querySelector(".persona-flex-col");if(Jt)ne.style.display="none",re&&St&&!re.contains(St)&&re.insertBefore(St,re.firstChild);else{if(ne.style.display="",ne.style.height=zt,ne.style.width=zt,re&&St&&(re.contains(ne)?ne.nextSibling!==St&&(ne.remove(),re.insertBefore(ne,St)):re.insertBefore(ne,St)),bt){let st=parseFloat(zt)||24,Lt=ge(bt,st*.6,"currentColor",1);Lt?ne.replaceChildren(Lt):ne.textContent=(Ip=me.agentIconText)!=null?Ip:"\u{1F4AC}"}else if(me.iconUrl){let st=ne.querySelector("img");if(st)st.src=me.iconUrl,st.style.height=zt,st.style.width=zt;else{let Lt=document.createElement("img");Lt.src=me.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=zt,Lt.style.width=zt,ne.replaceChildren(Lt)}}else{let st=ne.querySelector("svg"),Lt=ne.querySelector("img");(st||Lt)&&ne.replaceChildren(),ne.textContent=(Rp=me.agentIconText)!=null?Rp:"\u{1F4AC}"}let Vt=ne.querySelector("img");Vt&&(Vt.style.height=zt,Vt.style.width=zt)}}let qn=(Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showTitle,tn=(Dp=(Bp=r.layout)==null?void 0:Bp.header)==null?void 0:Dp.showSubtitle;if(Ee&&(Ee.style.display=qn===!1?"none":""),Ne&&(Ne.style.display=tn===!1?"none":""),S){((Op=(Np=r.layout)==null?void 0:Np.header)==null?void 0:Op.showCloseButton)===!1?S.style.display="none":S.style.display="";let St=(Fp=me.closeButtonSize)!=null?Fp:"32px",Vt=(_p=me.closeButtonPlacement)!=null?_p:"inline";S.style.height=St,S.style.width=St;let{closeButtonWrapper:st}=ze,Lt=Vt==="top-right",cn=st==null?void 0:st.classList.contains("persona-absolute");if(st&&Lt!==cn)if(st.remove(),Lt)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(st);else{let it=(jp=($p=me.clearChat)==null?void 0:$p.placement)!=null?jp:"inline",dn=(qp=(Up=me.clearChat)==null?void 0:Up.enabled)!=null?qp:!0;st.className=dn&&it==="inline"?"":"persona-ml-auto";let Hn=Se.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(st)}if(S.style.color=me.closeButtonColor||kn.actionIconColor,me.closeButtonBackgroundColor?(S.style.backgroundColor=me.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let it=me.closeButtonBorderWidth||"0px",dn=me.closeButtonBorderColor||"transparent";S.style.border=`${it} solid ${dn}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");me.closeButtonBorderRadius?(S.style.borderRadius=me.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(S.style.paddingLeft=me.closeButtonPaddingX,S.style.paddingRight=me.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),me.closeButtonPaddingY?(S.style.paddingTop=me.closeButtonPaddingY,S.style.paddingBottom=me.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let vn=(zp=me.closeButtonIconName)!=null?zp:"x",fr=(Vp=me.closeButtonIconText)!=null?Vp:"\xD7";S.innerHTML="";let Mn=ge(vn,"28px","currentColor",1);Mn?S.appendChild(Mn):S.textContent=fr;let Zt=(Kp=me.closeButtonTooltipText)!=null?Kp:"Close chat",Kn=(Gp=me.closeButtonShowTooltip)!=null?Gp:!0;if(S.setAttribute("aria-label",Zt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),Kn&&Zt)){let it=null,dn=()=>{if(it||!S)return;let qo=S.ownerDocument,Zs=qo.body;if(!Zs)return;it=Dr(qo,"div","persona-clear-chat-tooltip"),it.textContent=Zt;let ea=Dr(qo,"div");ea.className="persona-clear-chat-tooltip-arrow",it.appendChild(ea);let zo=S.getBoundingClientRect();it.style.position="fixed",it.style.zIndex=String(Eo),it.style.left=`${zo.left+zo.width/2}px`,it.style.top=`${zo.top-8}px`,it.style.transform="translate(-50%, -100%)",Zs.appendChild(it)},Hn=()=>{it&&it.parentNode&&(it.parentNode.removeChild(it),it=null)};st.addEventListener("mouseenter",dn),st.addEventListener("mouseleave",Hn),S.addEventListener("focus",dn),S.addEventListener("blur",Hn),st._cleanupTooltip=()=>{Hn(),st&&(st.removeEventListener("mouseenter",dn),st.removeEventListener("mouseleave",Hn)),S&&(S.removeEventListener("focus",dn),S.removeEventListener("blur",Hn))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Mt}=ze;if(Xe){let re=(Jp=me.clearChat)!=null?Jp:{},St=(Xp=re.enabled)!=null?Xp:!0,Vt=(Yp=(Qp=r.layout)==null?void 0:Qp.header)==null?void 0:Yp.showClearChat,st=Vt!==void 0?Vt:St,Lt=(Zp=re.placement)!=null?Zp:"inline";if(Mt){Mt.style.display=st?"":"none";let{closeButtonWrapper:cn}=ze;!H()&&cn&&!cn.classList.contains("persona-absolute")&&(st?cn.classList.remove("persona-ml-auto"):cn.classList.add("persona-ml-auto"));let vn=Lt==="top-right",fr=Mt.classList.contains("persona-absolute");if(!H()&&vn!==fr&&st){if(Mt.remove(),vn)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",Se.style.position="relative",Se.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let Zt=Se.querySelector(".persona-border-b-persona-divider"),Kn=ze.closeButtonWrapper;Zt&&Kn&&Kn.parentElement===Zt?Zt.insertBefore(Mt,Kn):Zt&&Zt.appendChild(Mt)}let Mn=ze.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(vn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(st){if(!H()){let it=(eu=re.size)!=null?eu:"32px";Xe.style.height=it,Xe.style.width=it}let cn=(tu=re.iconName)!=null?tu:"refresh-cw",vn=(nu=re.iconColor)!=null?nu:"";Xe.style.color=vn||kn.actionIconColor,Xe.innerHTML="";let fr=H()?"14px":"20px",Mn=ge(cn,fr,"currentColor",2);if(Mn&&Xe.appendChild(Mn),re.backgroundColor?(Xe.style.backgroundColor=re.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let it=re.borderWidth||"0px",dn=re.borderColor||"transparent";Xe.style.border=`${it} solid ${dn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");re.borderRadius?(Xe.style.borderRadius=re.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),re.paddingX?(Xe.style.paddingLeft=re.paddingX,Xe.style.paddingRight=re.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),re.paddingY?(Xe.style.paddingTop=re.paddingY,Xe.style.paddingBottom=re.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Zt=(ru=re.tooltipText)!=null?ru:"Clear chat",Kn=(ou=re.showTooltip)!=null?ou:!0;if(Xe.setAttribute("aria-label",Zt),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),Kn&&Zt)){let it=null,dn=()=>{if(it||!Xe)return;let qo=Xe.ownerDocument,Zs=qo.body;if(!Zs)return;it=Dr(qo,"div","persona-clear-chat-tooltip"),it.textContent=Zt;let ea=Dr(qo,"div");ea.className="persona-clear-chat-tooltip-arrow",it.appendChild(ea);let zo=Xe.getBoundingClientRect();it.style.position="fixed",it.style.zIndex=String(Eo),it.style.left=`${zo.left+zo.width/2}px`,it.style.top=`${zo.top-8}px`,it.style.transform="translate(-50%, -100%)",Zs.appendChild(it)},Hn=()=>{it&&it.parentNode&&(it.parentNode.removeChild(it),it=null)};Mt.addEventListener("mouseenter",dn),Mt.addEventListener("mouseleave",Hn),Xe.addEventListener("focus",dn),Xe.addEventListener("blur",Hn),Mt._cleanupTooltip=()=>{Hn(),Mt&&(Mt.removeEventListener("mouseenter",dn),Mt.removeEventListener("mouseleave",Hn)),Xe&&(Xe.removeEventListener("focus",dn),Xe.removeEventListener("blur",Hn))}}}}let rn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ra],sr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[as.message,as.messageAndClick];P=Wa({parsers:rn,handlers:sr,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=mf(r,P,pe),j.updateConfig(r),Vs(rt,j.getMessages(),ee),ls(),Lc(),ol(j.isStreaming());let zn=((su=r.voiceRecognition)==null?void 0:su.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((iu=(au=r.voiceRecognition)==null?void 0:au.provider)==null?void 0:iu.type)==="runtype";if(zn&&(_o||$o))if(!B||!ye){let re=ph(r.voiceRecognition,r.sendButton);re&&(B=re.micButton,ye=re.micButtonWrapper,Rt.insertBefore(ye,An),B.addEventListener("click",Ua),B.disabled=j.isStreaming())}else{let re=(lu=r.voiceRecognition)!=null?lu:{},St=(cu=r.sendButton)!=null?cu:{},Vt=(du=re.iconName)!=null?du:"mic",st=(pu=St.size)!=null?pu:"40px",Lt=(uu=re.iconSize)!=null?uu:st,cn=parseFloat(Lt)||24;B.style.width=Lt,B.style.height=Lt,B.style.minWidth=Lt,B.style.minHeight=Lt;let vn=(gu=(mu=re.iconColor)!=null?mu:St.textColor)!=null?gu:"currentColor";B.innerHTML="";let fr=ge(Vt,cn,vn,2);fr?B.appendChild(fr):B.textContent="\u{1F3A4}";let Mn=(fu=re.backgroundColor)!=null?fu:St.backgroundColor;Mn?B.style.backgroundColor=Mn:B.style.backgroundColor="",vn?B.style.color=vn:B.style.color="var(--persona-text, #111827)",re.borderWidth?(B.style.borderWidth=re.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),re.borderColor?B.style.borderColor=re.borderColor:B.style.borderColor="",re.paddingX?(B.style.paddingLeft=re.paddingX,B.style.paddingRight=re.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),re.paddingY?(B.style.paddingTop=re.paddingY,B.style.paddingBottom=re.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Zt=ye==null?void 0:ye.querySelector(".persona-send-button-tooltip"),Kn=(hu=re.tooltipText)!=null?hu:"Start voice recognition";if(((yu=re.showTooltip)!=null?yu:!1)&&Kn)if(Zt)Zt.textContent=Kn,Zt.style.display="";else{let dn=document.createElement("div");dn.className="persona-send-button-tooltip",dn.textContent=Kn,ye==null||ye.insertBefore(dn,B)}else Zt&&(Zt.style.display="none");ye.style.display="",B.disabled=j.isStreaming()}else B&&ye&&(ye.style.display="none",((xu=(bu=r.voiceRecognition)==null?void 0:bu.provider)==null?void 0:xu.type)==="runtype"?j.isVoiceActive()&&j.toggleVoice():Rr&&uo());if(((vu=r.attachments)==null?void 0:vu.enabled)===!0)if(!wt||!_e){let re=(wu=r.attachments)!=null?wu:{},Vt=(Au=((Cu=r.sendButton)!=null?Cu:{}).size)!=null?Au:"40px";Dt||(Dt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Dt.style.display="none",vt.insertBefore(Dt,te)),Ze||(Ze=document.createElement("input"),Ze.type="file",Ze.accept=((Su=re.allowedTypes)!=null?Su:Qr).join(","),Ze.multiple=((Tu=re.maxFiles)!=null?Tu:4)>1,Ze.style.display="none",Ze.setAttribute("aria-label","Attach files"),vt.insertBefore(Ze,te)),wt=y("div","persona-send-button-wrapper"),_e=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),_e.type="button",_e.setAttribute("aria-label",(Eu=re.buttonTooltipText)!=null?Eu:"Attach file");let st=(Mu=re.buttonIconName)!=null?Mu:"paperclip",Lt=Vt,cn=parseFloat(Lt)||40,vn=Math.round(cn*.6);_e.style.width=Lt,_e.style.height=Lt,_e.style.minWidth=Lt,_e.style.minHeight=Lt,_e.style.fontSize="18px",_e.style.lineHeight="1",_e.style.backgroundColor="transparent",_e.style.color="var(--persona-primary, #111827)",_e.style.border="none",_e.style.borderRadius="6px",_e.style.transition="background-color 0.15s ease",_e.addEventListener("mouseenter",()=>{_e.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),_e.addEventListener("mouseleave",()=>{_e.style.backgroundColor="transparent"});let fr=ge(st,vn,"currentColor",1.5);fr?_e.appendChild(fr):_e.textContent="\u{1F4CE}",_e.addEventListener("click",Kn=>{Kn.preventDefault(),Ze==null||Ze.click()}),wt.appendChild(_e);let Mn=(ku=re.buttonTooltipText)!=null?ku:"Attach file",Zt=y("div","persona-send-button-tooltip");Zt.textContent=Mn,wt.appendChild(Zt),lt.append(wt),!Ct&&Ze&&Dt&&(Ct=Zo.fromConfig(re),Ct.setPreviewsContainer(Dt),Ze.addEventListener("change",async()=>{Ct&&(Ze!=null&&Ze.files)&&(await Ct.handleFileSelect(Ze.files),Ze.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(gf(re.dropOverlay))}else{wt.style.display="";let re=(Lu=r.attachments)!=null?Lu:{};Ze&&(Ze.accept=((Pu=re.allowedTypes)!=null?Pu:Qr).join(","),Ze.multiple=((Iu=re.maxFiles)!=null?Iu:4)>1),Ct&&Ct.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else wt&&(wt.style.display="none"),Ct&&Ct.clearAttachments(),(Ru=Se.querySelector(".persona-attachment-drop-overlay"))==null||Ru.remove();let Xt=(Wu=r.sendButton)!=null?Wu:{},jo=(Hu=Xt.useIcon)!=null?Hu:!1,go=(Bu=Xt.iconText)!=null?Bu:"\u2191",fo=Xt.iconName,Kr=(Du=Xt.tooltipText)!=null?Du:"Send message",Uo=(Nu=Xt.showTooltip)!=null?Nu:!1,gr=(Ou=Xt.size)!=null?Ou:"40px",Wr=Xt.backgroundColor,Ye=Xt.textColor;if(jo){if(Ue.style.width=gr,Ue.style.height=gr,Ue.style.minWidth=gr,Ue.style.minHeight=gr,Ue.style.fontSize="18px",Ue.style.lineHeight="1",Ue.innerHTML="",Ye?Ue.style.color=Ye:Ue.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let re=parseFloat(gr)||24,St=(Ye==null?void 0:Ye.trim())||"currentColor",Vt=ge(fo,re,St,2);Vt?Ue.appendChild(Vt):Ue.textContent=go}else Ue.textContent=go;Ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wr?(Ue.style.backgroundColor=Wr,Ue.classList.remove("persona-bg-persona-primary")):(Ue.style.backgroundColor="",Ue.classList.add("persona-bg-persona-primary"))}else Ue.textContent=(_u=(Fu=r.copy)==null?void 0:Fu.sendButtonLabel)!=null?_u:"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",Wr?(Ue.style.backgroundColor=Wr,Ue.classList.remove("persona-bg-persona-accent")):Ue.classList.add("persona-bg-persona-accent"),Ye?Ue.style.color=Ye: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 Ot=An==null?void 0:An.querySelector(".persona-send-button-tooltip");if(Uo&&Kr)if(Ot)Ot.textContent=Kr,Ot.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=Kr,An==null||An.insertBefore(re,Ue)}else Ot&&(Ot.style.display="none");let Kt=(zu=($u=r.layout)==null?void 0:$u.contentMaxWidth)!=null?zu:H()?(qu=(Uu=(ju=r.launcher)==null?void 0:ju.composerBar)==null?void 0:Uu.contentMaxWidth)!=null?qu:"720px":void 0;Kt?(rt.style.maxWidth=Kt,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%",vt&&(vt.style.maxWidth=Kt,vt.style.marginLeft="auto",vt.style.marginRight="auto"),It&&(It.style.maxWidth=Kt,It.style.marginLeft="auto",It.style.marginRight="auto")):(rt.style.maxWidth="",rt.style.marginLeft="",rt.style.marginRight="",rt.style.width="",vt&&(vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight=""),It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""));let Ft=(Vu=r.statusIndicator)!=null?Vu:{},Qt=(Ku=Ft.visible)!=null?Ku:!0;if(yn.style.display=Qt?"":"none",j){let re=j.getStatus();jt(yn,(Vt=>{var st,Lt,cn,vn;return Vt==="idle"?(st=Ft.idleText)!=null?st:wn.idle:Vt==="connecting"?(Lt=Ft.connectingText)!=null?Lt:wn.connecting:Vt==="connected"?(cn=Ft.connectedText)!=null?cn:wn.connected:Vt==="error"?(vn=Ft.errorText)!=null?vn:wn.error:wn[Vt]})(re),Ft,re)}yn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kt=Ft.align==="left"?"persona-text-left":Ft.align==="center"?"persona-text-center":"persona-text-right";yn.classList.add(kt)},open(){F()&&qt(!0,"api")},close(){F()&&qt(!1,"api")},toggle(){F()&&qt(!O,"api")},clearChat(){Sn=!1,j.clearMessages(),Lr.clear(),Wn();try{localStorage.removeItem(js),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${js}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==js)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 c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),l!=null&&l.clear)try{let m=l.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(),Q==null||Q.reset(),He==null||He.update()},setMessage(c){return!te||j.isStreaming()?!1:(!O&&F()&&qt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(j.isStreaming())return!1;let m=(c==null?void 0:c.trim())||te.value.trim();return m?(!O&&F()&&qt(!0,"system"),te.value="",te.style.height="auto",j.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return j.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(j.isVoiceActive()||(!O&&F()&&qt(!0,"system"),ut.manuallyDeactivated=!1,Rn(),j.toggleVoice().then(()=>{ut.active=j.isVoiceActive(),nr("user"),j.isVoiceActive()&&ys()})),!0):Rr?!0:Dc()?(!O&&F()&&qt(!0,"system"),ut.manuallyDeactivated=!1,Rn(),$a("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?j.isVoiceActive()?(j.toggleVoice().then(()=>{ut.active=!1,ut.manuallyDeactivated=!0,Rn(),nr("user"),Vr()}),!0):!1:Rr?(ut.manuallyDeactivated=!0,Rn(),uo("user"),!0):!1},injectMessage(c){return!O&&F()&&qt(!0,"system"),j.injectMessage(c)},injectAssistantMessage(c){!O&&F()&&qt(!0,"system");let m=j.injectAssistantMessage(c);return Z&&(Z=!1,Me&&(clearTimeout(Me),Me=null),setTimeout(()=>{j&&!j.isStreaming()&&j.continueConversation()},100)),m},injectUserMessage(c){return!O&&F()&&qt(!0,"system"),j.injectUserMessage(c)},injectSystemMessage(c){return!O&&F()&&qt(!0,"system"),j.injectSystemMessage(c)},injectMessageBatch(c){return!O&&F()&&qt(!0,"system"),j.injectMessageBatch(c)},injectComponentDirective(c){return!O&&F()&&qt(!0,"system"),j.injectComponentDirective(c)},injectTestMessage(c){!O&&F()&&qt(!0,"system"),j.injectTestEvent(c)},async connectStream(c,m){return j.connectStream(c,m)},__pushEventStreamEvent(c){K&&(Q==null||Q.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!oe||!K||Or()},hideEventStream(){G&&dr()},isEventStreamVisible(){return G},showArtifacts(){cr(r)&&(Sn=!1,In(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(Sn=!0,In())},upsertArtifact(c){return cr(r)?(Sn=!1,j.upsertArtifact(c)):null},selectArtifact(c){cr(r)&&j.selectArtifact(c)},clearArtifacts(){cr(r)&&j.clearArtifacts()},getArtifacts(){var c;return(c=j==null?void 0:j.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=j==null?void 0:j.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!O&&!H()||!te?!1:(te.focus(),!0)},async resolveApproval(c,m,h){let T=j.getMessages().find(D=>{var z;return D.variant==="approval"&&((z=D.approval)==null?void 0:z.id)===c});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${c}`);if(T.approval.toolType==="webmcp"){j.resolveWebMcpApproval(T.id,m);return}return j.resolveApproval(T.approval,m,h)},getMessages(){return j.getMessages()},getStatus(){return j.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(c){x(c)},on(c,m){return i.on(c,m)},off(c,m){i.off(c,m)},isOpen(){return F()&&O},isVoiceActive(){return ut.active},toggleReadAloud(c){j.toggleReadAloud(c)},stopReadAloud(){j.stopSpeaking()},getReadAloudState(c){return j.getReadAloudState(c)},onReadAloudChange(c){return j.onReadAloudChange(c)},getState(){return{open:F()&&O,launcherEnabled:L,voiceActive:ut.active,streaming:j.isStreaming()}},showCSATFeedback(c){!O&&F()&&qt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let h=Ki({onSubmit:async(b,T)=>{var D;j.isClientTokenMode()&&await j.submitCSATFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!O&&F()&&qt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let h=Gi({onSubmit:async(b,T)=>{var D;j.isClientTokenMode()&&await j.submitNPSFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return j.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return j.submitNPSFeedback(c,m)},destroy(){Fo!=null&&(clearInterval(Fo),Fo=null),gt.forEach(c=>c()),he.remove(),pt==null||pt.remove(),en==null||en.destroy(),ln==null||ln.remove(),Mr&&S.removeEventListener("click",Mr)}};if((((Ud=n==null?void 0:n.debugTools)!=null?Ud:!1)||!!r.debug)&&typeof window!="undefined"){let c=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,gt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=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===c)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",m),gt.push(()=>{window.removeEventListener("persona:focusInput",m)}),oe){let $=ie=>{let le=ie.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&nn.showEventStream()},N=ie=>{let le=ie.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",N),gt.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",N)})}let h=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&nn.showArtifacts()},b=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&nn.hideArtifacts()},T=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==c||N!=null&&N.artifact&&nn.upsertArtifact(N.artifact)},D=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==c||typeof(N==null?void 0:N.id)=="string"&&nn.selectArtifact(N.id)},z=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===c)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",z),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",z)})}let or=cx(r.persistState);if(or&&F()){let c=dx(or.storage),m=`${or.keyPrefix}widget-open`,h=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let T=((qd=or.persist)==null?void 0:qd.openState)&&c.getItem(m)==="true",D=((zd=or.persist)==null?void 0:zd.voiceState)&&c.getItem(h)==="true",z=((Vd=or.persist)==null?void 0:Vd.voiceState)&&c.getItem(b)==="true";if(T&&setTimeout(()=>{nn.open(),setTimeout(()=>{var $;if(D||z)nn.startVoiceRecognition();else if(($=or.persist)!=null&&$.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(Kd=or.persist)!=null&&Kd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(Gd=or.persist)!=null&&Gd.voiceState&&(i.on("voice:state",$=>{c.setItem(h,$.active?"true":"false")}),i.on("user:message",$=>{c.setItem(b,$.viaVoice?"true":"false")})),or.clearOnChatClear){let $=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},N=()=>$();window.addEventListener("persona:clear-chat",N),gt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return g&&F()&&setTimeout(()=>{nn.open()},0),fs(),Da||tm().then(()=>{j&&(cs++,Lr.clear(),Vs(rt,j.getMessages(),ee))}).catch(()=>{}),nn};var px=(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},ux=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},mx=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gx=(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.")},ff=(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"},uc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},hf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",uc(e)},cc=e=>{e.style.transition=""},dc=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=""},pc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Qi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},fx=(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))},hx=(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)},yf=(e,t,n,r,o,s,a)=>{var v,x,M,E,P,L;let i=Jn(s),d=i.reveal==="push";fx(e,t,n,r,d),hx(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 l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(E=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?E:640,g=l!=null?l.innerWidth<=u:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),dc(t),cc(r),hf(r),pc(n),Qi(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((L=(P=s==null?void 0:s.launcher)==null?void 0:P.zIndex)!=null?L: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"),hf(r),ux(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",dc(t),cc(r),pc(n),Qi(o,r);let k=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=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=k,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",cc(r),uc(r),Qi(o,r);let k=px(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-k:0:a?0:-k;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+k}px`,t.style.transition=C,t.style.marginLeft=`${W}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="",dc(t),uc(r),pc(n),Qi(o,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!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",mx(r,i.maxHeight),r.style.overflow=k||W?"hidden":"visible",r.style.transition=C,k&&(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")}},yx=(e,t)=>{let n=e.ownerDocument.createElement("div");return ff(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){ff(n,r)},destroy(){n.remove()}}},bx=(e,t)=>{var L,k,I,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"),l=n.createElement("aside"),p=n.createElement("div"),u=(k=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||k?(C=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),Jn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{yf(a,i,d,l,p,t,u)}),g.observe(a))},x=!1,M=()=>{yf(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,gx(a,Jn(t)))},E=a.ownerDocument.defaultView,P=()=>{M()};return E==null||E.addEventListener("resize",P),Jn(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(W){let _=W.launcherEnabled?W.open:!0;u!==_&&(u=_,M())},updateConfig(W){var _,U;t=W,((U=(_=t==null?void 0:t.launcher)==null?void 0:_.enabled)!=null?U:!0)===!1&&(u=!0),M()},destroy(){E==null||E.removeEventListener("resize",P),f(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ha=(e,t)=>on(t)?bx(e,t):yx(e,t);var mc={},xx=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},vx=()=>{try{if(typeof mc!="undefined"&&mc.url)return new URL("../widget.css",mc.url).href}catch{}return null},bf=(e,t)=>{let n=vx(),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)}},gc=e=>{var M;let t=xx(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ha(t,o),a,i=[],d=(E,P)=>{var C,W;let k=!((W=(C=P==null?void 0:P.launcher)==null?void 0:C.enabled)!=null?W:!0)||on(P),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),k&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let _=E.attachShadow({mode:"open"});_.appendChild(I),bf(_,r)}else E.appendChild(I),bf(E,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let E=d(s.host,o);a=Xi(E,o,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),(M=e.onChatReady)==null||M.call(e);let f=E=>{g(),s.destroy(),s=Ha(t,E),o=E,u()},v={update(E){var W,_,U,H,F,O;let P={...o,...E,launcher:{...(W=o==null?void 0:o.launcher)!=null?W:{},...(_=E==null?void 0:E.launcher)!=null?_:{},dock:{...(H=(U=o==null?void 0:o.launcher)==null?void 0:U.dock)!=null?H:{},...(O=(F=E==null?void 0:E.launcher)==null?void 0:F.dock)!=null?O:{}}}},L=on(o),k=on(P),I=ko(o),C=ko(P);if(L!==k||I!==C){f(P);return}o=P,s.updateConfig(o),a.update(E),l()},destroy(){g(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(E,P,L){if(P==="host")return s.host;if(P in E)return Reflect.get(E,P,L);let k=a[P];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Af=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),wx=new Set(["button","a","input","select","textarea","details","summary"]),Cx=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),fc=/\b(product|card|item|listing|result)\b/i,yc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ax=3e3,Sx=100;function Sf(e){let t=typeof e.className=="string"?e.className:"";if(fc.test(t)||e.id&&fc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&fc.test(r.value))return!0}return!1}function Tf(e){var t;return yc.test(((t=e.textContent)!=null?t:"").trim())}function Ef(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 Tx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function xf(e){let t=e.match(yc);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 Ex(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 Mx="commerce-card",kx="result-card";function wf(e){return!Sf(e)||!Tf(e)||!Ef(e)&&!Tx(e)?0:5200}function Cf(e){var r;return!Sf(e)||Tf(e)||!Ef(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 bc=[{id:Mx,scoreElement(e){return wf(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||yc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(wf(e)===0)return null;let{title:n,href:r}=vf(e),o=(p=(l=xf(((d=e.textContent)!=null?d:"").trim()))!=null?l:xf(t.text))!=null?p:"",s=Ex(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
112
|
`)}},{id:kx,scoreElement(e){return Cf(e)},formatSummary(e,t){if(Cf(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
113
|
`)}}];function Lx(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Px(e){var p,u,g,f,v,x,M,E,P,L,k,I,C;let t=(p=e.options)!=null?p:{},n=(g=(u=t.maxElements)!=null?u:e.maxElements)!=null?g:80,r=(v=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",o=(M=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?M:200,s=(P=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?P:!0,a=(L=t.root)!=null?L:e.root,i=(k=t.mode)!=null?k:"structured",d=(I=t.maxCandidates)!=null?I:Math.max(500,n*10),l=(C=e.rules)!=null?C:bc;return i==="simple"&&e.rules&&e.rules.length>0?(Lx(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function hc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Ix=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Rx(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"||wx.has(t)||n&&Cx.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Mf(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 Wx(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 l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function xc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${hc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Ix){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${hc(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=>hc(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 Hx(e){return e==="static"?Sx:Ax}function kf(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:xc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Rx(e),attributes:Wx(e)}}function Bx(e,t,n,r){let o=Hx(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 Dx(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function Nx(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 l=i,p=l.tagName.toLowerCase();if(Af.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Mf(l)){i=a.nextNode();continue}let u=kf(l,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(M=>M==="role");if(!g&&!f){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=Bx(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;Dx(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,n);f&&(p=f)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function Ox(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,l=d.tagName.toLowerCase();if(Af.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Mf(d)){s=o.nextNode();continue}let p=kf(d,e.maxTextLength),u=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!u&&!g){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 Lf(e={}){var r;let t=Px(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Ox(t,n):Nx(t,n):[]}var Yi=100;function Pf(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(`
|
|
@@ -124,7 +124,7 @@ ${a.join(`
|
|
|
124
124
|
${a.join(`
|
|
125
125
|
`)}`)}return r.join(`
|
|
126
126
|
|
|
127
|
-
`)}function If(){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 Rf(){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 Wf(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:Nr(e.colors.primary,.95),100:Nr(e.colors.primary,.9),200:Nr(e.colors.primary,.8),300:Nr(e.colors.primary,.7),400:Nr(e.colors.primary,.6),500:e.colors.primary,600:Nr(e.colors.primary,.8),700:Nr(e.colors.primary,.7),800:Nr(e.colors.primary,.6),900:Nr(e.colors.primary,.5),950:Nr(e.colors.primary,.45)}}),{...t,palette:n}}}}function Hf(){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 Bf(){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 Nr(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 Df(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Fx={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"}}},Nf={components:{panel:{borderRadius:"0",shadow:"none"}}},vc={id:"shop",label:"Shopping Assistant",config:{theme:Fx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:
|
|
127
|
+
`)}function If(){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 Rf(){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 Wf(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:Nr(e.colors.primary,.95),100:Nr(e.colors.primary,.9),200:Nr(e.colors.primary,.8),300:Nr(e.colors.primary,.7),400:Nr(e.colors.primary,.6),500:e.colors.primary,600:Nr(e.colors.primary,.8),700:Nr(e.colors.primary,.7),800:Nr(e.colors.primary,.6),900:Nr(e.colors.primary,.5),950:Nr(e.colors.primary,.45)}}),{...t,palette:n}}}}function Hf(){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 Bf(){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 Nr(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 Df(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Fx={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"}}},Nf={components:{panel:{borderRadius:"0",shadow:"none"}}},vc={id:"shop",label:"Shopping Assistant",config:{theme:Fx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},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?"]}},wc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Nf}},Cc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Nf}},Ac={shop:vc,minimal:wc,fullscreen:Cc};function Of(e){return Ac[e]}var Ff=gc;function to(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function _x(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 _f=`({ 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
|
|
@@ -444,5 +444,5 @@ ${a.join(`
|
|
|
444
444
|
min-height: 300px;
|
|
445
445
|
}
|
|
446
446
|
}
|
|
447
|
-
`;function Qx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Xx,document.head.appendChild(e)}function Yx(e,t){let n=e.clientWidth-Tc*2-Qf,r=e.clientHeight-Tc*2-Qf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Zx(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 Yf(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Qx();let p=Math.max(0,Math.min(r,n.length-1)),u=o,g=s,f=null,v=1,x=!1,M=y("div","persona-dc-root"),E=y("div","persona-dc-toolbar"),P=y("div","persona-dc-toolbar-lead"),L=y("div","persona-dc-toolbar-trail"),k=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>
|
|
447
|
+
`;function Qx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Xx,document.head.appendChild(e)}function Yx(e,t){let n=e.clientWidth-Tc*2-Qf,r=e.clientHeight-Tc*2-Qf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Zx(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 Yf(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Qx();let p=Math.max(0,Math.min(r,n.length-1)),u=o,g=s,f=null,v=1,x=!1,M=y("div","persona-dc-root"),E=y("div","persona-dc-toolbar"),P=y("div","persona-dc-toolbar-lead"),L=y("div","persona-dc-toolbar-trail"),k=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Q(-1)}),I=y("div");I.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 W=y("span","persona-dc-title-text"),_=y("span","persona-dc-title-chevron"),U=ge("chevron-down",12,"currentColor",2);U&&_.appendChild(U),C.append(W,_);let H=y("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let F=!1;function O(){H.innerHTML="";for(let fe=0;fe<n.length;fe++){let Ke=n[fe],tt=y("button","persona-dc-dropdown-item");tt.type="button",tt.setAttribute("role","option"),tt.setAttribute("aria-current",fe===p?"true":"false");let jt=y("span");if(jt.textContent=Ke.title,tt.appendChild(jt),Ke.description){let Qe=y("span","persona-dc-dropdown-desc");Qe.textContent=Ke.description,tt.appendChild(Qe)}tt.addEventListener("click",()=>{Me(),He(fe)}),H.appendChild(tt)}}function Z(){F=!F,H.style.display=F?"":"none",C.setAttribute("aria-expanded",F?"true":"false"),F&&O()}function Me(){F&&(F=!1,H.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",fe=>{fe.stopPropagation(),Z()});let pe=()=>Me();document.addEventListener("click",pe),I.append(C,H);let ee=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Q(1)}),Ae=y("span","persona-dc-counter");P.append(k,I,ee,Ae);let Le=null;i&&(Le=Ma({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:fe=>{u=fe,se.dataset.device=u,f=null,G()}}),L.appendChild(Le.element));let oe=null;if(a){let fe=y("div","persona-dc-zoom-controls"),Ke=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Qe=f!=null?f:v;f=Math.max(Jf,Qe-Gf),G()}});oe=y("span","persona-dc-zoom-level"),oe.title="Reset to 100%",oe.style.cursor="pointer",oe.addEventListener("click",()=>{f=1,G()});let tt=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Qe=f!=null?f:v;f=Math.min(Xf,Qe+Gf),G()}}),jt=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,G()}});fe.append(Ke,oe,tt,jt),L.appendChild(fe)}if(d){let fe=y("div","persona-dc-separator");L.appendChild(fe);let Ke=Ma({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:tt=>{g=tt,se.dataset.colorScheme=g,Be()}});L.appendChild(Ke.element)}let Ce=y("div","persona-dc-separator");L.appendChild(Ce);let ce=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});L.appendChild(ce),E.append(P,L);let ae=y("div","persona-dc-stage"),se=y("div","persona-dc-iframe-wrapper");se.dataset.device=u,se.dataset.colorScheme=g;let xe=y("iframe","persona-dc-iframe");xe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),xe.setAttribute("loading","lazy"),xe.title=n[p].title,se.appendChild(xe),ae.appendChild(se),M.append(E,ae),e.appendChild(M);function Be(){var fe;try{let Ke=(fe=xe.contentDocument)==null?void 0:fe.body;if(!Ke)return;g==="dark"?Ke.classList.add("theme-dark"):Ke.classList.remove("theme-dark")}catch{}}xe.addEventListener("load",()=>Be());function K(){let fe=n[p];W.textContent=fe.title,Ae.textContent=`${p+1} / ${n.length}`,xe.title=fe.title}function Q(fe){let Ke=((p+fe)%n.length+n.length)%n.length;He(Ke)}function He(fe){fe<0||fe>=n.length||(p=fe,xe.src=n[p].url,K(),l==null||l(p,n[p]))}function G(){var tt;if(x)return;let fe=(tt=Kf[u])!=null?tt:Kf.desktop;v=Yx(ae,fe);let Ke=Math.max(Jf,Math.min(Xf,f!=null?f:v));Zx(se,xe,fe,Ke,u),oe&&(oe.textContent=`${Math.round(Ke*100)}%`)}let ue=new ResizeObserver(()=>G());ue.observe(ae),K(),xe.src=n[p].url,requestAnimationFrame(()=>G());function je(){x||(x=!0,ue.disconnect(),document.removeEventListener("click",pe),M.remove())}return{element:M,goTo:He,next:()=>Q(1),prev:()=>Q(-1),getIndex:()=>p,setDevice(fe){u=fe,se.dataset.device=fe,Le==null||Le.setSelected(fe),f=null,G()},setColorScheme(fe){g=fe,se.dataset.colorScheme=fe},setZoom(fe){f=fe,G()},destroy:je}}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
|