@runtypelabs/persona 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +31 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.global.js +21 -19
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +31 -29
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +24 -22
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +24 -22
- package/dist/theme-editor.d.cts +1 -1
- package/dist/theme-editor.d.ts +1 -1
- package/dist/widget.css +14 -0
- package/package.json +1 -1
- package/src/components/message-bubble.ts +7 -0
- package/src/styles/widget.css +14 -0
- package/src/types.ts +1 -1
- package/src/ui.ts +6 -1
- package/src/utils/streaming-table.test.ts +100 -0
- package/src/utils/streaming-table.ts +103 -0
package/dist/index.cjs
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
"use strict";var nh=Object.create;var $a=Object.defineProperty;var rh=Object.getOwnPropertyDescriptor;var oh=Object.getOwnPropertyNames;var sh=Object.getPrototypeOf,ah=Object.prototype.hasOwnProperty;var Xs=(e,t)=>()=>(e&&(t=e(e=0)),t);var cl=(e,t)=>{for(var n in t)$a(e,n,{get:t[n],enumerable:!0})},qu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oh(t))!ah.call(e,s)&&s!==n&&$a(e,s,{get:()=>t[s],enumerable:!(r=rh(t,s))||r.enumerable});return e};var dl=(e,t,n)=>(n=e!=null?nh(sh(e)):{},qu(t||!e||!e.__esModule?$a(n,"default",{value:e,enumerable:!0}):n,e)),ih=e=>qu($a({},"__esModule",{value:!0}),e);var Ku={};cl(Ku,{DOMPurify:()=>Vu.default,Marked:()=>zu.Marked});var zu,Vu,Gu=Xs(()=>{"use strict";zu=require("marked"),Vu=dl(require("dompurify"),1)});var Ts,Ml=Xs(()=>{"use strict";Ts=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var s;this.sampleRate=t;let r=Math.max(0,(s=n.prebufferMs)!=null?s:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=r,s.connect(n.destination);let o=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=o:this.nextStartTime<o&&(this.nextStartTime=o,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}}});function oy(e){return e.replace(/\/+$/,"")}async function sy(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var ii,jm=Xs(()=>{"use strict";Ml();ii=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 Ts(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var s,o,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${oy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(s=n.voice)!=null?s:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await sy(p));let m=p.body.getReader();for(;;){let{done:f,value:g}=await m.read();if(t!==this.generation){await m.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(o=this.opts).onError)==null||a.call(o,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var li,Um=Xs(()=>{"use strict";li=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var s;r=!0,(s=n.onStart)==null||s.call(n)},onEnd:()=>{var s;return(s=n.onEnd)==null?void 0:s.call(n)},onError:s=>{var o,a,i;if(r){(o=n.onError)==null||o.call(n,s);return}(i=(a=this.options).onFallback)==null||i.call(a,s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,s;(n=(t=this.primary).destroy)==null||n.call(t),(s=(r=this.fallback).destroy)==null||s.call(r)}}});var qm={};cl(qm,{FallbackSpeechEngine:()=>li,RuntypeSpeechEngine:()=>ii});var zm=Xs(()=>{"use strict";jm();Um()});var kx={};cl(kx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Al,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Sl,ASK_USER_QUESTION_TOOL_NAME:()=>ta,AgentWidgetClient:()=>Ko,AgentWidgetSession:()=>Ms,AttachmentManager:()=>Xo,BrowserSpeechEngine:()=>Co,DEFAULT_COMPONENTS:()=>Rl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>di,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Qn,DEFAULT_PALETTE:()=>Pl,DEFAULT_SEMANTIC:()=>Il,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>xc,PRESET_FULLSCREEN:()=>bc,PRESET_MINIMAL:()=>yc,PRESET_SHOP:()=>hc,ReadAloudController:()=>Qo,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ka,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>vl,SUGGEST_REPLIES_TOOL_NAME:()=>yr,THEME_ZONES:()=>Zm,VERSION:()=>lr,WEBMCP_TOOL_PREFIX:()=>Vr,WebMcpBridge:()=>xs,accessibilityPlugin:()=>yf,animationsPlugin:()=>bf,applyThemeVariables:()=>So,attachHeaderToContainer:()=>Zo,brandPlugin:()=>xf,buildComposer:()=>Rs,buildDefaultHeader:()=>_l,buildHeader:()=>Yr,buildHeaderWithLayout:()=>Is,buildMinimalHeader:()=>$l,builtInClientToolsForDispatch:()=>oa,collectEnrichedPageContext:()=>ff,componentRegistry:()=>Zr,createActionManager:()=>ka,createAgentExperience:()=>Vi,createAskUserQuestionBubble:()=>wm,createBestAvailableVoiceProvider:()=>ai,createBubbleWithLayout:()=>Tg,createCSATFeedback:()=>Ui,createComboButton:()=>Ti,createComponentMiddleware:()=>Jg,createComponentStreamParser:()=>Fi,createDefaultSanitizer:()=>ul,createDemoCarousel:()=>Of,createDirectivePostprocessor:()=>rm,createDropdownMenu:()=>Mo,createFlexibleJsonStreamParser:()=>Tm,createIconButton:()=>qt,createImagePart:()=>Wm,createJsonStreamParser:()=>ti,createLabelButton:()=>wa,createLocalStorageAdapter:()=>Oi,createMarkdownProcessor:()=>Ys,createMarkdownProcessorFromConfig:()=>zo,createMessageActions:()=>Gl,createNPSFeedback:()=>qi,createPlainTextParser:()=>Za,createPlugin:()=>Cf,createRegexJsonParser:()=>ei,createStandardBubble:()=>Ws,createTextPart:()=>la,createTheme:()=>Ls,createThemeObserver:()=>gi,createToggleGroup:()=>Ca,createTypingIndicator:()=>es,createVoiceProvider:()=>wo,createWidgetHostLayout:()=>La,createXmlParser:()=>ni,default:()=>Tf,defaultActionHandlers:()=>ns,defaultJsonActionParser:()=>Ma,defaultParseRules:()=>gc,detectColorScheme:()=>ma,directivePostprocessor:()=>om,ensureAskUserQuestionSheet:()=>Cs,escapeHtml:()=>Rr,extractComponentDirectiveFromMessage:()=>ji,fileToImagePart:()=>Hm,formatEnrichedContext:()=>hf,generateAssistantMessageId:()=>Go,generateCodeSnippet:()=>If,generateMessageId:()=>km,generateStableSelector:()=>fc,generateUserMessageId:()=>As,getActiveTheme:()=>Ps,getColorScheme:()=>Hl,getDisplayText:()=>Pm,getHeaderLayout:()=>jl,getImageParts:()=>Rm,getPreset:()=>Af,hasComponentDirective:()=>$i,hasImages:()=>Im,headerLayouts:()=>Ei,highContrastPlugin:()=>wf,initAgentWidget:()=>dc,isAskUserQuestionMessage:()=>Kr,isComponentDirectiveType:()=>Gg,isDockedMountMode:()=>on,isSuggestRepliesMessage:()=>ra,isVoiceSupported:()=>da,isWebMcpToolName:()=>ho,latestAgentSuggestions:()=>Ga,listRegisteredStreamAnimations:()=>hg,markdownPostprocessor:()=>pl,mergeWithDefaults:()=>pi,normalizeContent:()=>Lm,parseAskUserQuestionPayload:()=>Gr,parseSuggestRepliesPayload:()=>Cl,pickBestVoice:()=>Es,pluginRegistry:()=>Ea,reducedMotionPlugin:()=>vf,registerStreamAnimationPlugin:()=>gg,removeAskUserQuestionSheet:()=>xo,renderComponentDirective:()=>_i,renderLoadingIndicatorWithFallback:()=>Kl,renderLucideIcon:()=>xe,resolveDockConfig:()=>Xn,resolveSanitizer:()=>bs,resolveTokens:()=>ui,stripWebMcpPrefix:()=>Ua,themeToCssVariables:()=>mi,unregisterStreamAnimationPlugin:()=>fg,validateImageFile:()=>Bm,validateTheme:()=>Wl});module.exports=ih(kx);var Yu=require("marked"),Zu=dl(require("dompurify"),1);var Ju=null,ys=null,hs=null;var Qu=e=>{ys=e},Xu=()=>ys?Promise.resolve(ys):hs||(Ju?(hs=Ju().then(e=>(ys=e,e)),hs):(hs=Promise.resolve().then(()=>(Gu(),Ku)).then(e=>(ys=e,e)),hs)),qo=()=>ys;Qu({Marked:Yu.Marked,DOMPurify:Zu.default});var lh=e=>{if(e)return e},Ys=e=>{let t=null;return n=>{var s,o;let r=qo();if(!r)return Rr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(s=i==null?void 0:i.gfm)!=null?s:!0,breaks:(o=i==null?void 0:i.breaks)!=null?o:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=lh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},zo=e=>e?Ys({markedOptions:e.options,renderer:e.renderer}):Ys(),ch=Ys(),pl=e=>ch(e),Rr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),tm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),em=e=>`%%FORM_PLACEHOLDER_${e}%%`,nm=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=em(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=em(t.length);return t.push({token:o,type:s}),o}),n},rm=e=>{let t=zo(e);return n=>{let r=[],s=nm(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${tm(i)}"></div>`;o=o.replace(d,p)}),o}},om=e=>{let t=[],n=nm(e,t),r=pl(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${tm(o)}"></div>`;r=r.replace(a,d)}),r};var dh={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},ph=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ul=()=>{let e=null;return t=>{let n=qo();if(!n)return Rr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(s,o)=>{if(o.attrName==="src"||o.attrName==="href"){let a=o.attrValue;a.toLowerCase().startsWith("data:")&&!ph.test(a)&&(o.attrValue="",o.keepAttr=!1)}})}return e.sanitize(t,dh)}},bs=e=>e===!1?null:typeof e=="function"?e:ul();var Vr="webmcp:",ml=new Map,sm=e=>{var t;ml.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&ml.set(n.name,r)}},gl=e=>ml.get(Ua(e)),ja={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},am=null;function lm(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${uh(t.join(""))}`}function im(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function uh(e){let t=im(e,0).toString(36),n=im(e,2654435761).toString(36);return`${t}.${n}`}var xs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return ja.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}sm(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=gh(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let x=typeof document!="undefined"&&!!document.modelContext;return hr(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Ua(t),a;try{a=await s.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return hr(`Failed to read WebMCP registry: ${v}`)}sm(a);let i=a.find(x=>x.name===o);if(!i)return hr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return hr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d=gl(o),c={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let p=new AbortController,m=!1,f=setTimeout(()=>{m=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let x=await s.executeTool(i,bh(n),{signal:p.signal});return fh(x)}catch(x){if(m)return hr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return hr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(am?await am():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ja.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,ja.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:hh;try{return await n(t)}catch(s){return ja.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>mh(t,r))}},Ua=e=>e.startsWith(Vr)?e.slice(Vr.length):e,ho=e=>e.startsWith(Vr),mh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},gh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},fh=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:xh(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),hh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=yh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
1
|
+
"use strict";var ah=Object.create;var $a=Object.defineProperty;var ih=Object.getOwnPropertyDescriptor;var lh=Object.getOwnPropertyNames;var ch=Object.getPrototypeOf,dh=Object.prototype.hasOwnProperty;var Xs=(e,t)=>()=>(e&&(t=e(e=0)),t);var cl=(e,t)=>{for(var n in t)$a(e,n,{get:t[n],enumerable:!0})},qu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of lh(t))!dh.call(e,s)&&s!==n&&$a(e,s,{get:()=>t[s],enumerable:!(r=ih(t,s))||r.enumerable});return e};var dl=(e,t,n)=>(n=e!=null?ah(ch(e)):{},qu(t||!e||!e.__esModule?$a(n,"default",{value:e,enumerable:!0}):n,e)),ph=e=>qu($a({},"__esModule",{value:!0}),e);var Ku={};cl(Ku,{DOMPurify:()=>Vu.default,Marked:()=>zu.Marked});var zu,Vu,Gu=Xs(()=>{"use strict";zu=require("marked"),Vu=dl(require("dompurify"),1)});var Ts,Ml=Xs(()=>{"use strict";Ts=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var s;this.sampleRate=t;let r=Math.max(0,(s=n.prebufferMs)!=null?s:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=r,s.connect(n.destination);let o=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=o:this.nextStartTime<o&&(this.nextStartTime=o,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}}});function py(e){return e.replace(/\/+$/,"")}async function uy(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 ii,Vm=Xs(()=>{"use strict";Ml();ii=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 Ts(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var s,o,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${py(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(s=n.voice)!=null?s:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await uy(p));let m=p.body.getReader();for(;;){let{done:f,value:g}=await m.read();if(t!==this.generation){await m.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(o=this.opts).onError)==null||a.call(o,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var li,Km=Xs(()=>{"use strict";li=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var s;r=!0,(s=n.onStart)==null||s.call(n)},onEnd:()=>{var s;return(s=n.onEnd)==null?void 0:s.call(n)},onError:s=>{var o,a,i;if(r){(o=n.onError)==null||o.call(n,s);return}(i=(a=this.options).onFallback)==null||i.call(a,s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,s;(n=(t=this.primary).destroy)==null||n.call(t),(s=(r=this.fallback).destroy)==null||s.call(r)}}});var Gm={};cl(Gm,{FallbackSpeechEngine:()=>li,RuntypeSpeechEngine:()=>ii});var Jm=Xs(()=>{"use strict";Vm();Km()});var Bx={};cl(Bx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Al,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Sl,ASK_USER_QUESTION_TOOL_NAME:()=>ta,AgentWidgetClient:()=>Ko,AgentWidgetSession:()=>Ms,AttachmentManager:()=>Xo,BrowserSpeechEngine:()=>Co,DEFAULT_COMPONENTS:()=>Rl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>di,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Qn,DEFAULT_PALETTE:()=>Pl,DEFAULT_SEMANTIC:()=>Il,DEFAULT_WIDGET_CONFIG:()=>Nt,PRESETS:()=>xc,PRESET_FULLSCREEN:()=>bc,PRESET_MINIMAL:()=>yc,PRESET_SHOP:()=>hc,ReadAloudController:()=>Qo,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ka,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>vl,SUGGEST_REPLIES_TOOL_NAME:()=>yr,THEME_ZONES:()=>rg,VERSION:()=>lr,WEBMCP_TOOL_PREFIX:()=>Vr,WebMcpBridge:()=>xs,accessibilityPlugin:()=>wf,animationsPlugin:()=>Cf,applyThemeVariables:()=>So,attachHeaderToContainer:()=>Zo,brandPlugin:()=>Sf,buildComposer:()=>Rs,buildDefaultHeader:()=>_l,buildHeader:()=>Yr,buildHeaderWithLayout:()=>Is,buildMinimalHeader:()=>$l,builtInClientToolsForDispatch:()=>oa,collectEnrichedPageContext:()=>xf,componentRegistry:()=>Zr,createActionManager:()=>ka,createAgentExperience:()=>Vi,createAskUserQuestionBubble:()=>Tm,createBestAvailableVoiceProvider:()=>ai,createBubbleWithLayout:()=>Lg,createCSATFeedback:()=>Ui,createComboButton:()=>Ti,createComponentMiddleware:()=>Zg,createComponentStreamParser:()=>Fi,createDefaultSanitizer:()=>ul,createDemoCarousel:()=>jf,createDirectivePostprocessor:()=>rm,createDropdownMenu:()=>Mo,createFlexibleJsonStreamParser:()=>Lm,createIconButton:()=>qt,createImagePart:()=>Nm,createJsonStreamParser:()=>ti,createLabelButton:()=>wa,createLocalStorageAdapter:()=>Oi,createMarkdownProcessor:()=>Ys,createMarkdownProcessorFromConfig:()=>zo,createMessageActions:()=>Gl,createNPSFeedback:()=>qi,createPlainTextParser:()=>Za,createPlugin:()=>Ef,createRegexJsonParser:()=>ei,createStandardBubble:()=>Ws,createTextPart:()=>la,createTheme:()=>Ls,createThemeObserver:()=>gi,createToggleGroup:()=>Ca,createTypingIndicator:()=>es,createVoiceProvider:()=>wo,createWidgetHostLayout:()=>La,createXmlParser:()=>ni,default:()=>Lf,defaultActionHandlers:()=>ns,defaultJsonActionParser:()=>Ma,defaultParseRules:()=>gc,detectColorScheme:()=>ma,directivePostprocessor:()=>om,ensureAskUserQuestionSheet:()=>Cs,escapeHtml:()=>Rr,extractComponentDirectiveFromMessage:()=>ji,fileToImagePart:()=>Om,formatEnrichedContext:()=>vf,generateAssistantMessageId:()=>Go,generateCodeSnippet:()=>Bf,generateMessageId:()=>Rm,generateStableSelector:()=>fc,generateUserMessageId:()=>As,getActiveTheme:()=>Ps,getColorScheme:()=>Hl,getDisplayText:()=>Hm,getHeaderLayout:()=>jl,getImageParts:()=>Dm,getPreset:()=>kf,hasComponentDirective:()=>$i,hasImages:()=>Bm,headerLayouts:()=>Ei,highContrastPlugin:()=>Tf,initAgentWidget:()=>dc,isAskUserQuestionMessage:()=>Kr,isComponentDirectiveType:()=>Yg,isDockedMountMode:()=>on,isSuggestRepliesMessage:()=>ra,isVoiceSupported:()=>da,isWebMcpToolName:()=>ho,latestAgentSuggestions:()=>Ga,listRegisteredStreamAnimations:()=>vg,markdownPostprocessor:()=>pl,mergeWithDefaults:()=>pi,normalizeContent:()=>Wm,parseAskUserQuestionPayload:()=>Gr,parseSuggestRepliesPayload:()=>Cl,pickBestVoice:()=>Es,pluginRegistry:()=>Ea,reducedMotionPlugin:()=>Af,registerStreamAnimationPlugin:()=>bg,removeAskUserQuestionSheet:()=>xo,renderComponentDirective:()=>_i,renderLoadingIndicatorWithFallback:()=>Kl,renderLucideIcon:()=>xe,resolveDockConfig:()=>Xn,resolveSanitizer:()=>bs,resolveTokens:()=>ui,stripWebMcpPrefix:()=>Ua,themeToCssVariables:()=>mi,unregisterStreamAnimationPlugin:()=>xg,validateImageFile:()=>Fm,validateTheme:()=>Wl});module.exports=ph(Bx);var Yu=require("marked"),Zu=dl(require("dompurify"),1);var Ju=null,ys=null,hs=null;var Qu=e=>{ys=e},Xu=()=>ys?Promise.resolve(ys):hs||(Ju?(hs=Ju().then(e=>(ys=e,e)),hs):(hs=Promise.resolve().then(()=>(Gu(),Ku)).then(e=>(ys=e,e)),hs)),qo=()=>ys;Qu({Marked:Yu.Marked,DOMPurify:Zu.default});var uh=e=>{if(e)return e},Ys=e=>{let t=null;return n=>{var s,o;let r=qo();if(!r)return Rr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(s=i==null?void 0:i.gfm)!=null?s:!0,breaks:(o=i==null?void 0:i.breaks)!=null?o:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=uh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},zo=e=>e?Ys({markedOptions:e.options,renderer:e.renderer}):Ys(),mh=Ys(),pl=e=>mh(e),Rr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),tm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),em=e=>`%%FORM_PLACEHOLDER_${e}%%`,nm=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=em(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=em(t.length);return t.push({token:o,type:s}),o}),n},rm=e=>{let t=zo(e);return n=>{let r=[],s=nm(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${tm(i)}"></div>`;o=o.replace(d,p)}),o}},om=e=>{let t=[],n=nm(e,t),r=pl(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${tm(o)}"></div>`;r=r.replace(a,d)}),r};var gh={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"]},fh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ul=()=>{let e=null;return t=>{let n=qo();if(!n)return Rr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(s,o)=>{if(o.attrName==="src"||o.attrName==="href"){let a=o.attrValue;a.toLowerCase().startsWith("data:")&&!fh.test(a)&&(o.attrValue="",o.keepAttr=!1)}})}return e.sanitize(t,gh)}},bs=e=>e===!1?null:typeof e=="function"?e:ul();var sm=/^\s*\|?[\s:|-]*-[\s:|-]*$/,am=e=>e.includes("|"),im=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())},hh=e=>`| ${e.join(" | ")} |`,yh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,bh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),lm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let r=0;r<t.length-1;r++){let s=t[r],o=t[r+1];if(!am(s)||sm.test(s)||!sm.test(o))continue;let a=im(s).length;if(a<1)continue;let i=yh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let c=t[d];if(c.trim()===""||!am(c))break;let p=hh(bh(im(c),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
|
|
3
|
+
`):e};var Vr="webmcp:",ml=new Map,cm=e=>{var t;ml.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&ml.set(n.name,r)}},gl=e=>ml.get(Ua(e)),ja={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},dm=null;function um(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${xh(t.join(""))}`}function pm(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function xh(e){let t=pm(e,0).toString(36),n=pm(e,2654435761).toString(36);return`${t}.${n}`}var xs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return ja.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}cm(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=wh(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let x=typeof document!="undefined"&&!!document.modelContext;return hr(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Ua(t),a;try{a=await s.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return hr(`Failed to read WebMCP registry: ${v}`)}cm(a);let i=a.find(x=>x.name===o);if(!i)return hr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return hr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d=gl(o),c={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let p=new AbortController,m=!1,f=setTimeout(()=>{m=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let x=await s.executeTool(i,Th(n),{signal:p.signal});return Ch(x)}catch(x){if(m)return hr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return hr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(dm?await dm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ja.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,ja.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:Sh;try{return await n(t)}catch(s){return ja.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>vh(t,r))}},Ua=e=>e.startsWith(Vr)?e.slice(Vr.length):e,ho=e=>e.startsWith(Vr),vh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},wh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Ch=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Eh(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),Sh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ah(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
2
4
|
|
|
3
5
|
Arguments:
|
|
4
6
|
${t}`:"")+(e.description?`
|
|
5
7
|
|
|
6
|
-
${e.description}`:"");return window.confirm(n)},yh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},bh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},xh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var yo=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(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[o,a]of Object.entries(t.attrs))r.setAttribute(o,a);if(t.style){let o=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(o[i]=d)}}let s=n.filter(o=>o!=null);return s.length>0&&r.append(...s),r},Zs=(...e)=>e.filter(Boolean).join(" ");var ta="ask_user_question",ea=8,vs="data-persona-ask-sheet-for",vh="Other",wh="Other\u2026",dm="Type your own answer here",pm="Send",Ch="Next",Sh="Back",Ah="Submit all",Th="Skip",Eh=3,fl="data-ask-current-index",hl="data-ask-question-count",um="data-ask-answers",yl="data-ask-grouped",mm="data-ask-layout",Mh=e=>e.layout==="pills"?"pills":"rows",kh=e=>e.getAttribute(mm)==="pills"?"pills":"rows",cm=!1,gm=e=>e.replace(/["\\]/g,"\\$&"),Kr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ta,qa=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Gr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,yo.parse)(s,yo.STR|yo.OBJ|yo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},na=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ea&&!cm&&(cm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ea}.`)),t.slice(0,ea)},Lh=e=>{var t;return(t=na(e)[0])!=null?t:null},Ph=(e,t)=>{var n;return(n=na(e)[t])!=null?n:null},fm=(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))},hm=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=y("span","persona-ask-row-check");r.appendChild(s)}else{let s=y("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Ih=(e,t,n,r)=>{let o=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}o.appendChild(a);let d=hm(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Rh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Wh=(e,t,n,r)=>{var p,m,f;let o=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Eh;g++)o.appendChild(Rh(r));return o}if(d.forEach((g,x)=>{o.appendChild(Ih(g,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?vh:wh;if(r==="rows"){let x=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),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:dm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:g),v.appendChild(M),x.appendChild(v);let S=hm(r,a,d.length);S&&x.appendChild(S),o.appendChild(x)}else{let x=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:g,o.appendChild(x)}}return o},ym=(e,t)=>{var o,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:dm,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:pm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Hh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:pm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Bh=(e,t,n)=>{var c,p,m,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=y("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(c=n.backLabel)!=null?c:Sh,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Th,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:Ah:(f=n.nextLabel)!=null?f:Ch,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Vo=e=>{let t=e.getAttribute(um);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},bm=(e,t)=>{e.setAttribute(um,JSON.stringify(t))},ir=e=>{var n;let t=Number((n=e.getAttribute(fl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Dh=(e,t)=>{e.setAttribute(fl,String(Math.max(0,Math.floor(t))))},ws=e=>{var n;let t=Number((n=e.getAttribute(hl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},bo=e=>e.getAttribute(yl)==="true",Nh=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Oh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},za=(e,t)=>{let{payload:n}=Gr(t),r=na(n),s=Vo(e),o={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(s,d)&&(o[c]=s[d]))}),o},xm=e=>{let t=Vo(e),n=ir(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},vm=e=>{if(!bo(e))return;let t=Vo(e),n=ir(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},bl=(e,t,n)=>{let r=qa(n),s=kh(e),{payload:o,complete:a}=Gr(t),i=bo(e),d=ir(e),c=ws(e),p=i?Ph(o,d):Lh(o),m=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let R=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=Wh(p,r,a,s);v.replaceWith(R)}if(s!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(ym(r,s))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!M?e.appendChild(Hh(r)):(!m||i)&&M&&M.remove(),e.setAttribute("data-multi-select",m?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Bh(d,c,r);S?S.replaceWith(R):e.appendChild(R)}else S&&S.remove();xm(e),vm(e)},Fh=(e,t,n)=>{let r=qa(t),s=Mh(r),o=e.toolCall.id,a=na(n),i=Math.max(1,a.length),d=i>1,c=Nh(e,a),p=d?Oh(e,i):0,m=y("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(vs,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(hl,String(i)),m.setAttribute(fl,String(p)),m.setAttribute(yl,d?"true":"false"),m.setAttribute(mm,s),bm(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),fm(m,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),m.appendChild(f);let M=y("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),s!=="rows"&&m.appendChild(ym(r,s)),bl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},_h=(e,t,n)=>{let{payload:r}=Gr(t),s=Math.max(1,na(r).length);s>ws(e)&&(e.setAttribute(hl,String(s)),s>1&&!bo(e)&&e.setAttribute(yl,"true")),bl(e,t,n)},wm=(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=qa(t);fm(n,r);let s=y("span","persona-ask-stub-label"),{complete:o}=Gr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Cs=(e,t,n)=>{if(!n||!Kr(e)||qa(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${vs}]`).forEach(c=>{c.getAttribute(vs)!==s&&c.remove()});let a=n.querySelector(`[${vs}="${gm(s)}"]`);if(a){_h(a,e,t);return}let{payload:i}=Gr(e),d=Fh(e,t,i);n.appendChild(d)},xo=(e,t)=>{if(!e)return;let n=t?`[${vs}="${gm(t)}"]`:`[${vs}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},xl=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),vo=(e,t)=>{let n=Vo(e),r=ir(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,bm(e,n),xm(e),vm(e)},Va=(e,t,n,r)=>{let s=ws(e),o=Math.max(0,Math.min(s-1,r));Dh(e,o),bl(e,t,n)};var yr="suggest_replies";var vl={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},Ka={name:yr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:vl,origin:"sdk",annotations:{readOnlyHint:!0}},wl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ra=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===yr},Cl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Ga=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!ra(r))continue;let s=Cl((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Cm=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 Sl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ea,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},Al={name:ta,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:Sl,origin:"sdk",annotations:{readOnlyHint:!0}},oa=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(Al),Cm(e)&&t.push(Ka),t};var Jr=require("partial-json"),Ja=e=>e.replace(/\\n/g,`
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ss=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)}}
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},Ah=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)}},Th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Eh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var yo=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(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[o,a]of Object.entries(t.attrs))r.setAttribute(o,a);if(t.style){let o=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(o[i]=d)}}let s=n.filter(o=>o!=null);return s.length>0&&r.append(...s),r},Zs=(...e)=>e.filter(Boolean).join(" ");var ta="ask_user_question",ea=8,vs="data-persona-ask-sheet-for",Mh="Other",kh="Other\u2026",gm="Type your own answer here",fm="Send",Lh="Next",Ph="Back",Ih="Submit all",Rh="Skip",Wh=3,fl="data-ask-current-index",hl="data-ask-question-count",hm="data-ask-answers",yl="data-ask-grouped",ym="data-ask-layout",Hh=e=>e.layout==="pills"?"pills":"rows",Bh=e=>e.getAttribute(ym)==="pills"?"pills":"rows",mm=!1,bm=e=>e.replace(/["\\]/g,"\\$&"),Kr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ta,qa=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Gr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,yo.parse)(s,yo.STR|yo.OBJ|yo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},na=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ea&&!mm&&(mm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ea}.`)),t.slice(0,ea)},Dh=e=>{var t;return(t=na(e)[0])!=null?t:null},Nh=(e,t)=>{var n;return(n=na(e)[t])!=null?n:null},xm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},vm=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=y("span","persona-ask-row-check");r.appendChild(s)}else{let s=y("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Oh=(e,t,n,r)=>{let o=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}o.appendChild(a);let d=vm(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Fh=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},_h=(e,t,n,r)=>{var p,m,f;let o=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Wh;g++)o.appendChild(Fh(r));return o}if(d.forEach((g,x)=>{o.appendChild(Oh(g,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Mh:kh;if(r==="rows"){let x=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),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:gm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:g),v.appendChild(M),x.appendChild(v);let S=vm(r,a,d.length);S&&x.appendChild(S),o.appendChild(x)}else{let x=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:g,o.appendChild(x)}}return o},wm=(e,t)=>{var o,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:gm,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:fm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},$h=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:fm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},jh=(e,t,n)=>{var c,p,m,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=y("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(c=n.backLabel)!=null?c:Ph,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Rh,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:Ih:(f=n.nextLabel)!=null?f:Lh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Vo=e=>{let t=e.getAttribute(hm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Cm=(e,t)=>{e.setAttribute(hm,JSON.stringify(t))},ir=e=>{var n;let t=Number((n=e.getAttribute(fl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Uh=(e,t)=>{e.setAttribute(fl,String(Math.max(0,Math.floor(t))))},ws=e=>{var n;let t=Number((n=e.getAttribute(hl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},bo=e=>e.getAttribute(yl)==="true",qh=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},zh=(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)))},za=(e,t)=>{let{payload:n}=Gr(t),r=na(n),s=Vo(e),o={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(s,d)&&(o[c]=s[d]))}),o},Sm=e=>{let t=Vo(e),n=ir(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Am=e=>{if(!bo(e))return;let t=Vo(e),n=ir(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},bl=(e,t,n)=>{let r=qa(n),s=Bh(e),{payload:o,complete:a}=Gr(t),i=bo(e),d=ir(e),c=ws(e),p=i?Nh(o,d):Dh(o),m=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let R=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=_h(p,r,a,s);v.replaceWith(R)}if(s!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(wm(r,s))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!M?e.appendChild($h(r)):(!m||i)&&M&&M.remove(),e.setAttribute("data-multi-select",m?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=jh(d,c,r);S?S.replaceWith(R):e.appendChild(R)}else S&&S.remove();Sm(e),Am(e)},Vh=(e,t,n)=>{let r=qa(t),s=Hh(r),o=e.toolCall.id,a=na(n),i=Math.max(1,a.length),d=i>1,c=qh(e,a),p=d?zh(e,i):0,m=y("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(vs,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(hl,String(i)),m.setAttribute(fl,String(p)),m.setAttribute(yl,d?"true":"false"),m.setAttribute(ym,s),Cm(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),xm(m,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),m.appendChild(f);let M=y("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),s!=="rows"&&m.appendChild(wm(r,s)),bl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Kh=(e,t,n)=>{let{payload:r}=Gr(t),s=Math.max(1,na(r).length);s>ws(e)&&(e.setAttribute(hl,String(s)),s>1&&!bo(e)&&e.setAttribute(yl,"true")),bl(e,t,n)},Tm=(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=qa(t);xm(n,r);let s=y("span","persona-ask-stub-label"),{complete:o}=Gr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Cs=(e,t,n)=>{if(!n||!Kr(e)||qa(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${vs}]`).forEach(c=>{c.getAttribute(vs)!==s&&c.remove()});let a=n.querySelector(`[${vs}="${bm(s)}"]`);if(a){Kh(a,e,t);return}let{payload:i}=Gr(e),d=Vh(e,t,i);n.appendChild(d)},xo=(e,t)=>{if(!e)return;let n=t?`[${vs}="${bm(t)}"]`:`[${vs}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},xl=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),vo=(e,t)=>{let n=Vo(e),r=ir(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Cm(e,n),Sm(e),Am(e)},Va=(e,t,n,r)=>{let s=ws(e),o=Math.max(0,Math.min(s-1,r));Uh(e,o),bl(e,t,n)};var yr="suggest_replies";var vl={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},Ka={name:yr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:vl,origin:"sdk",annotations:{readOnlyHint:!0}},wl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ra=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===yr},Cl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Ga=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!ra(r))continue;let s=Cl((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Em=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 Sl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ea,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},Al={name:ta,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:Sl,origin:"sdk",annotations:{readOnlyHint:!0}},oa=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(Al),Em(e)&&t.push(Ka),t};var Jr=require("partial-json"),Ja=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ss=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)}},Gh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Mm=e=>e.status==="complete"?Gh(e):e.status==="pending"?"Waiting":"",Jh=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var km=e=>e.status==="complete"?Jh(e):"Using tool...",Qa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},aa=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Qa(t)},Xa=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Qa(t)},Tl=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=aa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ya=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&sa(r,n.slice(o,a.index),[]),a[1]!==void 0?sa(r,a[1],["bold"]):a[2]!==void 0?sa(r,a[2],["italic"]):a[3]!==void 0&&sa(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&sa(r,n.slice(o),[]),r},sa=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Qh=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
8
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ia=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Za=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ei=()=>{var t;let e=Uh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},ti=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,Jr.parse)(n,Jr.STR|Jr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ja(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ja(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Tm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ja(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ja(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,Jr.parse)(o,Jr.STR|Jr.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},ni=()=>{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 Em="4.0.0";var lr=Em;var zh="https://api.runtype.com/v1/dispatch",ri="https://api.runtype.com";function Vh(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var El=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Kh(e){switch(e){case"json":return ti;case"regex-json":return ei;case"xml":return ni;default:return Za}}var Mm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Mm(n);if(!Mm(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=ia(e);return ia(t)!==null&&a===null?t:e}var Ko=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:zh,this.headers={"Content-Type":"application/json","X-Persona-Version":lr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Kh(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new xs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(El).map(k=>{var I,A,H;return{id:k.id,role:k.role,content:(H=(A=(I=k.contentParts)!=null?I:k.llmContent)!=null?A:k.rawContent)!=null?H:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),x=g?lm(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=g&&v&&this.lastSentClientToolsFingerprint===x,S=!1,R=null,O;for(let k=0;;k++){let A={...m,...g&&(S||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),O=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(A),signal:r.signal}),O.status===409&&k===0&&g){let H=await O.json().catch(()=>null);if((H==null?void 0:H.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}R=H!=null?H:{error:"Chat request failed"}}break}if(!O.ok){let k=R!=null?R:await O.json().catch(()=>({error:"Chat request failed"}));if(O.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:A}),A}if(O.status===429){let A=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let I=new Error(k.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!O.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(O.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||ri}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(El).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...oa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(El).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...oa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var sn,xr,yn,Ke;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=E=>{let me=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,ke=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,Ee=E.tools?E.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...E,reasoning:me,toolCall:ke,tools:Ee}},m=E=>{if(E.role!=="assistant"||E.variant)return!0;let me=Array.isArray(E.contentParts)&&E.contentParts.length>0,ke=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||me||ke||!!E.stopReason},f=E=>{m(E)&&n({type:"message",message:p(E)})},g=null,x=null,v={current:null},M={current:null},S=null,R="",O=new Map,k=new Map,I=new Map,A=new Map,H=new Map,D={lastId:null,byStep:new Map},N={lastId:null,byCall:new Map},L=E=>{if(E==null)return null;try{return String(E)}catch{return null}},U=E=>{var me,ke,Ee,Re,nt;return L((nt=(Re=(Ee=(ke=(me=E.stepId)!=null?me:E.step_id)!=null?ke:E.step)!=null?Ee:E.parentId)!=null?Re:E.flowStepId)!=null?nt:E.flow_step_id)},V=E=>{var me,ke,Ee,Re,nt,Qe,ut;return L((ut=(Qe=(nt=(Re=(Ee=(ke=(me=E.callId)!=null?me:E.call_id)!=null?ke:E.requestId)!=null?Ee:E.request_id)!=null?Re:E.toolCallId)!=null?nt:E.tool_call_id)!=null?Qe:E.stepId)!=null?ut:E.step_id)},ne=r,Ie=!1,Ue=()=>{if(g)return g;let E,me=S;return!Ie&&ne?(E=ne,Ie=!0):ne&&me?E=`${ne}_${me}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:E,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(g),g},Ae=(E,me)=>{D.lastId=me,E&&D.byStep.set(E,me)},Le=(E,me)=>{var nt;let ke=(nt=E.reasoningId)!=null?nt:E.id,Ee=U(E);if(ke){let Qe=String(ke);return Ae(Ee,Qe),Qe}if(Ee){let Qe=D.byStep.get(Ee);if(Qe)return D.lastId=Qe,Qe}if(D.lastId&&!me)return D.lastId;if(!me)return null;let Re=`reason-${c()}`;return Ae(Ee,Re),Re},_e=E=>{let me=A.get(E);if(me)return me;let ke={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return A.set(E,ke),f(ke),ke},ye=(E,me)=>{N.lastId=me,E&&N.byCall.set(E,me)},De=new Set,ie=new Map,X=new Set,re=new Map,ce=E=>{if(!E)return!1;let me=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},oe=(E,me)=>{var nt;let ke=(nt=E.toolId)!=null?nt:E.id,Ee=V(E);if(ke){let Qe=String(ke);return ye(Ee,Qe),Qe}if(Ee){let Qe=N.byCall.get(Ee);if(Qe)return N.lastId=Qe,Qe}if(N.lastId&&!me)return N.lastId;if(!me)return null;let Re=`tool-${c()}`;return ye(Ee,Re),Re},J=E=>{let me=H.get(E);if(me)return me;let ke={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return H.set(E,ke),f(ke),ke},te=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let me=Number(E);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let ke=Date.parse(E);if(!Number.isNaN(ke))return ke}return Date.now()},ze=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Q=new Map,le=new Map,We=new Map,we=(E,me,ke)=>{var ut;let Ee=We.get(E);Ee||(Ee=[],We.set(E,Ee));let Re=0,nt=Ee.length;for(;Re<nt;){let Rt=Re+nt>>>1;Ee[Rt].seq<me?Re=Rt+1:nt=Rt}((ut=Ee[Re])==null?void 0:ut.seq)===me?Ee[Re]={seq:me,text:ke}:Ee.splice(Re,0,{seq:me,text:ke});let Qe="";for(let Rt=0;Rt<Ee.length;Rt++)Qe+=Ee[Rt].text;return Qe},Ye=(E,me)=>{let ke=ze(me),Ee=le.get(E.id),Re=Gh(Ee,ke);E.rawContent=Re;let nt=Q.get(E.id),Qe=K=>{var Me;let ue=(Me=E.content)!=null?Me:"";K.trim()!==""&&(ue.trim().length===0||K.startsWith(ue)||K.trimStart().startsWith(ue.trim()))&&(E.content=K)},ut=()=>{var K;if(nt){let ue=(K=nt.close)==null?void 0:K.call(nt);ue instanceof Promise&&ue.catch(()=>{})}Q.delete(E.id),le.delete(E.id),E.streaming=!1,f(E)};if(!nt){Qe(ke),ut();return}let Rt=ia(Re);if(Rt!==null&&Rt.trim()!==""){Qe(Rt),ut();return}let q=K=>{var xt;let ue=typeof K=="string"?K:(xt=K==null?void 0:K.text)!=null?xt:null;if(ue!==null&&ue.trim()!=="")return ue;let Me=nt.getExtractedText();return Me!==null&&Me.trim()!==""?Me:ke},at;try{at=nt.processChunk(Re)}catch{Qe(ke),ut();return}if(at instanceof Promise){at.then(K=>{Qe(q(K)),ut()}).catch(()=>{Qe(ke),ut()});return}Qe(q(at)),ut()},Ge=null,Oe=(E,me,ke,Ee)=>{var Rt;E.rawContent=me,Q.has(E.id)||Q.set(E.id,this.createStreamParser());let Re=Q.get(E.id),nt=me.trim().startsWith("{")||me.trim().startsWith("[");if(nt&&le.set(E.id,me),Re.__isPlainTextParser===!0){E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E);return}let ut=Re.processChunk(me);if(ut instanceof Promise)ut.then(q=>{var K;let at=typeof q=="string"?q:(K=q==null?void 0:q.text)!=null?K:null;at!==null&&at.trim()!==""?(E.content=at,f(E)):!nt&&!me.trim().startsWith("<")&&(E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E)});else{let q=typeof ut=="string"?ut:(Rt=ut==null?void 0:ut.text)!=null?Rt:null;q!==null&&q.trim()!==""?(E.content=q,f(E)):!nt&&!me.trim().startsWith("<")&&(E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E))}},de=(E,me)=>{var Rt,q;let ke=me!=null?me:E.content;if(ke==null||ke===""){E.streaming=!1,f(E);return}let Ee=le.get(E.id),Re=Ee!=null?Ee:ze(ke);E.rawContent=Re;let nt=Q.get(E.id),Qe=null,ut=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=ia(Re)),Qe===null)){let at=nt.processChunk(Re);at instanceof Promise?(ut=!0,at.then(K=>{var Me;let ue=typeof K=="string"?K:(Me=K==null?void 0:K.text)!=null?Me:null;ue!==null&&(E.content=ue,E.streaming=!1,Q.delete(E.id),le.delete(E.id),f(E))}).catch(()=>{})):Qe=typeof at=="string"?at:(Rt=at==null?void 0:at.text)!=null?Rt:null}if(!ut){Qe!==null&&Qe.trim()!==""?E.content=Qe:le.has(E.id)||(E.content=ze(ke));let at=Q.get(E.id);if(at){let K=(q=at.close)==null?void 0:q.call(at);K instanceof Promise&&K.catch(()=>{}),Q.delete(E.id)}le.delete(E.id),E.streaming=!1,f(E)}},tt=(E,me,ke)=>{let Ee=k.get(E);if(Ee)return Ee;let Re={id:`nested-${me}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ke?{variant:ke}:{},...ke==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return k.set(E,Re),f(Re),Re},Y=[],pe,Ce=new Map,Ve=0,Pt="agent",Te=null,ge=null,hn=new Map,It=(sn=this.config.iterationDisplay)!=null?sn:"separate";for(pe=()=>{var E,me,ke,Ee,Re,nt,Qe,ut,Rt,q,at,K,ue,Me,xt,Zt,en,mn,Ht,rt,Wt,ct,Gt,Zn,Sn,tn,In,vr,vt,Nn,wr,Br,dr,yt,Lo,Cr,Po,Rn,rs,to,Dr,no,ro,Io,Ro,oo,Ct,On,Fn,An,At,er,tr,_n,so,Nr,ao,$n,Bt,Tn,nr,io,Or,lo,Sr,jn,be,dt,Qt,an,Ar,Fs,Fr,Wo,Tr,_,os,Er,Mr,_r,kr,pr,ss,Ia,Un,qn,ur,mr,Ho,$r,bn,Lr,as,Bo,is,Ra,ls,Wa,cs,ht,_s,rr,Wn,Ha,Ba;for(let co=0;co<Y.length;co++){let ot=Y[co].payloadType,w=Y[co].payload;if(ot==="reasoning_start"){let j=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&$){O.set(j,$),tt(j,$,"reasoning");continue}let G=(E=Le(w,!0))!=null?E:`reason-${c()}`,he=_e(G);he.reasoning=(me=he.reasoning)!=null?me:{id:G,status:"streaming",chunks:[]},he.reasoning.startedAt=(Ee=he.reasoning.startedAt)!=null?Ee:te((ke=w.startedAt)!=null?ke: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",f(he)}else if(ot==="reasoning_delta"){let j=typeof w.id=="string"?w.id:null;if(j&&O.has(j)&&k.has(j)){let $e=k.get(j),Ze=(Qe=(nt=(Re=w.reasoningText)!=null?Re:w.text)!=null?nt:w.delta)!=null?Qe:"";Ze&&w.hidden!==!0&&$e.reasoning&&($e.reasoning.chunks.push(String(Ze)),f($e));continue}let $=(Rt=(ut=Le(w,!1))!=null?ut:Le(w,!0))!=null?Rt:`reason-${c()}`,G=_e($);G.reasoning=(q=G.reasoning)!=null?q:{id:$,status:"streaming",chunks:[]},G.reasoning.startedAt=(K=G.reasoning.startedAt)!=null?K:te((at=w.startedAt)!=null?at:w.timestamp);let he=(xt=(Me=(ue=w.reasoningText)!=null?ue:w.text)!=null?Me:w.delta)!=null?xt:"";if(he&&w.hidden!==!0){let $e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if($e!==void 0){let Ze=we($,$e,String(he));G.reasoning.chunks=[Ze]}else G.reasoning.chunks.push(String(he))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=te((Zt=w.completedAt)!=null?Zt:w.timestamp);let $e=(en=G.reasoning.startedAt)!=null?en:Date.now();G.reasoning.durationMs=Math.max(0,((mn=G.reasoning.completedAt)!=null?mn:Date.now())-$e)}G.streaming=G.reasoning.status!=="complete",f(G)}else if(ot==="reasoning_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&O.has(j)&&k.has(j)){let Ze=k.get(j);if(Ze.reasoning){let Mt=typeof w.text=="string"?w.text:"";Mt&&Ze.reasoning.chunks.length===0&&Ze.reasoning.chunks.push(Mt),Ze.reasoning.status="complete",Ze.streaming=!1,f(Ze)}O.delete(j),k.delete(j);continue}let $=(rt=(Ht=Le(w,!1))!=null?Ht:Le(w,!0))!=null?rt:`reason-${c()}`,G=typeof w.text=="string"?w.text:"";!A.get($)&&(G||w.scope==="loop")&&_e($);let he=A.get($);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),G&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(G),he.reasoning.status="complete",he.reasoning.completedAt=te((Wt=w.completedAt)!=null?Wt:w.timestamp);let Ze=(ct=he.reasoning.startedAt)!=null?ct:Date.now();he.reasoning.durationMs=Math.max(0,((Gt=he.reasoning.completedAt)!=null?Gt:Date.now())-Ze),he.streaming=!1,f(he)}let $e=U(w);$e&&D.byStep.delete($e)}else if(ot==="tool_start"){g&&(g.streaming=!1,f(g),g=null),typeof w.iteration=="number"&&(Ve=w.iteration);let j=(Sn=(Zn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Zn:oe(w,!0))!=null?Sn:`tool-${c()}`,$=(tn=w.toolName)!=null?tn:w.name;if(ce($)){De.add(j);continue}ye(V(w),j);let G=J(j),he=(In=G.toolCall)!=null?In:{id:j,status:"pending"};he.name=$!=null?$:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(vt=he.startedAt)!=null?vt:te((vr=w.startedAt)!=null?vr:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,G.toolCall=he,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),f(G)}else if(ot==="tool_output_delta"){let j=(wr=(Nn=oe(w,!1))!=null?Nn:oe(w,!0))!=null?wr:`tool-${c()}`;if(De.has(j))continue;let $=J(j),G=(Br=$.toolCall)!=null?Br:{id:j,status:"running"};G.startedAt=(yt=G.startedAt)!=null?yt:te((dr=w.startedAt)!=null?dr:w.timestamp);let he=(Po=(Cr=(Lo=w.text)!=null?Lo:w.delta)!=null?Cr:w.message)!=null?Po:"";he&&(G.chunks=(Rn=G.chunks)!=null?Rn:[],G.chunks.push(String(he))),G.status="running",$.toolCall=G,$.streaming=!0;let $e=w.agentContext;($e||w.executionId)&&($.agentMetadata=(Dr=$.agentMetadata)!=null?Dr:{executionId:(rs=$e==null?void 0:$e.executionId)!=null?rs:w.executionId,iteration:(to=$e==null?void 0:$e.iteration)!=null?to:w.iteration}),f($)}else if(ot==="tool_complete"){let j=(ro=(no=oe(w,!1))!=null?no:oe(w,!0))!=null?ro:`tool-${c()}`;if(De.has(j)){De.delete(j);continue}let $=J(j),G=(Io=$.toolCall)!=null?Io:{id:j,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=te((Ro=w.completedAt)!=null?Ro:w.timestamp);let he=(oo=w.duration)!=null?oo:w.executionTime;if(typeof he=="number")G.durationMs=he;else{let Mt=(Ct=G.startedAt)!=null?Ct:Date.now();G.durationMs=Math.max(0,((On=G.completedAt)!=null?On:Date.now())-Mt)}$.toolCall=G,$.streaming=!1;let $e=w.agentContext;($e||w.executionId)&&($.agentMetadata=(At=$.agentMetadata)!=null?At:{executionId:(Fn=$e==null?void 0:$e.executionId)!=null?Fn:w.executionId,iteration:(An=$e==null?void 0:$e.iteration)!=null?An:w.iteration}),f($);let Ze=V(w);Ze&&N.byCall.delete(Ze)}else if(ot==="await"&&w.toolName){let j=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,$=(er=j!=null?j:w.toolId)!=null?er:`local-${c()}`,G=J($),he=w.toolName,$e=w.origin==="webmcp"&&!ho(he)?`webmcp:${he}`:he,Ze=ho($e),Mt=(tr=G.toolCall)!=null?tr:{id:$,status:"pending"};Mt.name=$e,Mt.args=w.parameters,Mt.status=Ze?"running":"complete",Mt.chunks=(_n=Mt.chunks)!=null?_n:[],Mt.startedAt=(ao=Mt.startedAt)!=null?ao:te((Nr=(so=w.startedAt)!=null?so:w.timestamp)!=null?Nr:w.awaitedAt),Ze?(Mt.completedAt=void 0,Mt.duration=void 0,Mt.durationMs=void 0):Mt.completedAt=($n=Mt.completedAt)!=null?$n:Mt.startedAt,G.toolCall=Mt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Tn=w.executionId)!=null?Tn:(Bt=G.agentMetadata)==null?void 0:Bt.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},f(G)}else if(ot==="text_start"){let j=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&$){O.set(j,$);continue}let G=g;G&&(Pt==="flow"?(de(G),Ge=G):(G.streaming=!1,f(G)),g=null),S=typeof w.id=="string"?w.id:S,R=""}else if(ot==="text_delta"){let j=typeof w.id=="string"?w.id:null,$=j?O.get(j):void 0;if(j&&$){let he=typeof w.delta=="string"?w.delta:"",$e=((nr=I.get(j))!=null?nr:"")+he;if(I.set(j,$e),$e.trim()==="")continue;let Ze=tt(j,$);Ze.agentMetadata={...Ze.agentMetadata,executionId:w.executionId,parentToolId:$},Oe(Ze,$e,he,void 0);continue}if(S=typeof w.id=="string"?w.id:S,Pt==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(R+=he,R.trim()==="")continue;let $e=Ue();$e.agentMetadata={executionId:w.executionId,iteration:w.iteration},Oe($e,R,he,void 0),x=$e;continue}let G=Ue();G.content+=(io=w.delta)!=null?io:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Te!=null?Te:void 0,agentName:ge==null?void 0:ge.agentName},x=G,f(G)}else if(ot==="text_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&O.has(j)){let G=k.get(j);G&&de(G),O.delete(j),I.delete(j),k.delete(j);continue}let $=g;$&&(Pt==="flow"?(de($),Ge=$):(((Or=$.content)!=null?Or:"")===""&&typeof w.text=="string"&&($.content=w.text),$.streaming=!1,f($)),g=null),S=null,R=""}else if(ot==="step_complete"){let j=w.stepType,$=w.executionType;if(j==="tool"||$==="context")continue;if(w.success===!1){let G=w.error,he=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((lo=G.message)!=null?lo:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let $e=g;$e&&$e.streaming&&($e.streaming=!1,f($e)),n({type:"status",status:"idle"});continue}{let G=Ge;Ge=null;let he=w.stopReason,$e=(Sr=w.result)==null?void 0:Sr.response;if(G)he&&(G.stopReason=he),$e!=null?Ye(G,$e):G.streaming!==!1&&(Q.delete(G.id),le.delete(G.id),G.streaming=!1,f(G));else{let Ze=$e!=null&&$e!=="";if(Ze||he){let Mt=Ue();he&&(Mt.stopReason=he),Ze?de(Mt,$e):(Mt.streaming=!1,f(Mt))}}continue}}else if(ot==="execution_start")Pt=w.kind==="flow"?"flow":"agent",Pt==="agent"&&(ge={executionId:w.executionId,agentId:(jn=w.agentId)!=null?jn:"virtual",agentName:(be=w.agentName)!=null?be:"",status:"running",currentIteration:0,maxTurns:(dt=w.maxTurns)!=null?dt:1,startedAt:te(w.startedAt)});else if(ot==="turn_start"){let j=typeof w.iteration=="number"?w.iteration:Ve;if(j!==Ve){if(ge&&(ge.currentIteration=j),It==="separate"&&j>1){let $=g;$&&($.streaming=!1,f($),hn.set(j-1,$),g=null)}Ve=j}Te=typeof w.id=="string"?w.id:null,x=null}else if(ot==="tool_input_delta"){let j=(Qt=w.toolCallId)!=null?Qt:N.lastId;if(j){let $=H.get(j);$!=null&&$.toolCall&&($.toolCall.chunks=(an=$.toolCall.chunks)!=null?an:[],$.toolCall.chunks.push((Ar=w.delta)!=null?Ar:""),f($))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let j=w.stopReason,$=g!=null?g:x;if(j&&$!==null){let G=w.id;(!G||((Fs=$.agentMetadata)==null?void 0:Fs.turnId)===G)&&($.stopReason=j,f($))}Te===w.id&&(Te=null)}else if(ot==="media_start"){let j=String(w.id);Ce.set(j,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let j=Ce.get(String(w.id));j&&typeof w.delta=="string"&&j.parts.push(w.delta)}else if(ot==="media_complete"){let j=String(w.id),$=Ce.get(j);Ce.delete(j);let G=(Wo=(Fr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Fr:$==null?void 0:$.mediaType)!=null?Wo:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,$e=typeof w.url=="string"?w.url:$&&$.parts.length>0?$.parts.join(""):void 0,Ze=null;if(he)Ze={type:"media",data:he,mediaType:G};else if($e){let zn=G.toLowerCase();Ze={type:zn==="image"||zn.startsWith("image/")?"image-url":"file-url",url:$e,mediaType:G}}let Mt=(Tr=w.toolCallId)!=null?Tr:$==null?void 0:$.toolCallId,jr=Ze?[Ze]:[],Hn=[];for(let zn of jr){if(!zn||typeof zn!="object")continue;let gn=zn,po=typeof gn.type=="string"?gn.type:void 0,Ur=typeof gn.mediaType=="string"?gn.mediaType.toLowerCase():"",fn=null,Bn="";if(po==="media"){let Vn=typeof gn.data=="string"?gn.data:void 0;if(!Vn)continue;Bn=Ur.length>0?Ur:"application/octet-stream",fn=`data:${Bn};base64,${Vn}`}else if(po==="image-url"){let Vn=typeof gn.url=="string"?gn.url:void 0;if(!Vn)continue;Bn=Ur,fn=Vn}else if(po==="file-url"){let Vn=typeof gn.url=="string"?gn.url:void 0;if(!Vn)continue;Bn=Ur,fn=Vn}else continue;if(fn)if(po==="image-url"||Bn.startsWith("image/"))Hn.push({type:"image",image:fn,...Bn.includes("/")?{mimeType:Bn}:{}});else if(Bn.startsWith("audio/"))Hn.push({type:"audio",audio:fn,mimeType:Bn});else if(Bn.startsWith("video/"))Hn.push({type:"video",video:fn,mimeType:Bn});else{let Vn=Bn||"application/octet-stream";Hn.push({type:"file",data:fn,mimeType:Vn,filename:Vh(Vn)})}}if(Hn.length>0){let zn=c(),gn=Mt,Ur={id:`agent-media-${typeof gn=="string"&&gn.length>0?`${gn}-${zn}`:String(zn)}`,role:"assistant",content:"",contentParts:Hn,createdAt:new Date().toISOString(),streaming:!1,sequence:zn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ve}};f(Ur);let fn=g;fn&&(fn.streaming=!1,f(fn)),g=null,v.current=null}}else if(ot==="execution_complete"){let j=(_=w.kind)!=null?_:Pt;j==="agent"&&ge&&(ge.status=w.success?"complete":"error",ge.completedAt=te(w.completedAt),ge.stopReason=w.stopReason);let $=g;$&&(j==="flow"&&$.streaming!==!1?de($):($.streaming=!1,f($)),g=null),S=null,R="",Ge=null,n({type:"status",status:"idle"})}else if(ot==="execution_error"){let j=typeof w.error=="string"?w.error:(Er=(os=w.error)==null?void 0:os.message)!=null?Er:"Execution error";n({type:"error",error:new Error(j)})}else if(ot!=="ping"){if(ot==="approval_start"){let j=(Mr=w.approvalId)!=null?Mr:`approval-${c()}`,$={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(_r=ge==null?void 0:ge.agentId)!=null?_r:"virtual",executionId:(pr=(kr=w.executionId)!=null?kr:ge==null?void 0:ge.executionId)!=null?pr:"",toolName:(ss=w.toolName)!=null?ss:"",toolType:w.toolType,description:(Un=w.description)!=null?Un:`Execute ${(Ia=w.toolName)!=null?Ia:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f($)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let j=(qn=w.approvalId)!=null?qn:`approval-${c()}`,$={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(ur=ge==null?void 0:ge.agentId)!=null?ur:"virtual",executionId:(Ho=(mr=w.executionId)!=null?mr:ge==null?void 0:ge.executionId)!=null?Ho:"",toolName:($r=w.toolName)!=null?$r:"",toolType:w.toolType,description:(Lr=w.description)!=null?Lr:`Execute ${(bn=w.toolName)!=null?bn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f($)}else if(ot==="approval_complete"){let j=w.approvalId;if(j){let G={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:(as=w.decision)!=null?as:"approved",agentId:(Bo=ge==null?void 0:ge.agentId)!=null?Bo:"virtual",executionId:(Ra=(is=w.executionId)!=null?is:ge==null?void 0:ge.executionId)!=null?Ra:"",toolName:(ls=w.toolName)!=null?ls:"",description:(Wa=w.description)!=null?Wa:"",resolvedAt:Date.now()}};f(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=w.artifactType,$=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:$,artifactType:j,title:G,component:typeof w.component=="string"?w.component:void 0}),re.set($,{markdown:"",title:G}),!X.has($)){X.add($);let he={id:`artifact-ref-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:$,title:G,artifactType:j,status:"streaming"}})};ie.set($,he),f(he)}}else if(ot==="artifact_delta"){let j=String(w.id),$=typeof w.delta=="string"?w.delta:String((cs=w.delta)!=null?cs:"");n({type:"artifact_delta",id:j,artDelta:$});let G=re.get(j);G&&(G.markdown+=$)}else if(ot==="artifact_update"){let j=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:j,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let j=String(w.id);n({type:"artifact_complete",id:j});let $=ie.get(j);if($){$.streaming=!1;try{let G=JSON.parse((ht=$.rawContent)!=null?ht:"{}");if(G.props){G.props.status="complete";let he=re.get(j);he!=null&&he.markdown&&(G.props.markdown=he.markdown)}$.rawContent=JSON.stringify(G)}catch{}re.delete(j),f($),ie.delete(j)}}}else if(ot==="transcript_insert"){let j=w.message;if(!j||typeof j!="object")continue;let $=String((_s=j.id)!=null?_s:`msg-${c()}`),G=j.role,$e={id:$,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:c()};if(f($e),$e.rawContent)try{let Ze=JSON.parse($e.rawContent),Mt=(rr=Ze==null?void 0:Ze.props)==null?void 0:rr.artifactId;typeof Mt=="string"&&X.add(Mt)}catch{}g=null,v.current=null,Q.delete($),le.delete($)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let j=typeof w.error=="string"?w.error:((Wn=w.error)==null?void 0:Wn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(j)});let $=g;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(w.error instanceof Error)j=w.error;else if(ot==="dispatch_error"){let $=(Ha=w.message)!=null?Ha:w.error;$!=null&&$!==""&&(j=new Error(String($)))}else{let $=w.error;typeof $=="string"&&$!==""?j=new Error($):$!=null&&typeof $=="object"&&"message"in $&&(j=new Error(String((Ba=$.message)!=null?Ba:$)))}if(j){n({type:"error",error:j});let $=g;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}}}}}Y.length=0};;){let{done:E,value:me}=await s.read();if(E)break;a+=o.decode(me,{stream:!0});let ke=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 s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ia=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Za=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ei=()=>{var t;let e=Qh();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)}},ti=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,Jr.parse)(n,Jr.STR|Jr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ja(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ja(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Lm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ja(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ja(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,Jr.parse)(o,Jr.STR|Jr.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},ni=()=>{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 Pm="4.1.0";var lr=Pm;var Yh="https://api.runtype.com/v1/dispatch",ri="https://api.runtype.com";function Zh(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var El=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 ey(e){switch(e){case"json":return ti;case"regex-json":return ei;case"xml":return ni;default:return Za}}var Im=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ty(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Im(n);if(!Im(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=ia(e);return ia(t)!==null&&a===null?t:e}var Ko=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Yh,this.headers={"Content-Type":"application/json","X-Persona-Version":lr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:ey(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new xs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(El).map(k=>{var I,A,H;return{id:k.id,role:k.role,content:(H=(A=(I=k.contentParts)!=null?I:k.llmContent)!=null?A:k.rawContent)!=null?H:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),x=g?um(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=g&&v&&this.lastSentClientToolsFingerprint===x,S=!1,R=null,O;for(let k=0;;k++){let A={...m,...g&&(S||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),O=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(A),signal:r.signal}),O.status===409&&k===0&&g){let H=await O.json().catch(()=>null);if((H==null?void 0:H.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}R=H!=null?H:{error:"Chat request failed"}}break}if(!O.ok){let k=R!=null?R:await O.json().catch(()=>({error:"Chat request failed"}));if(O.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:A}),A}if(O.status===429){let A=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let I=new Error(k.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!O.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(O.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ri}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||ri}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(El).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...oa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(El).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...oa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var sn,xr,yn,Ke;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=E=>{let me=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,ke=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,Ee=E.tools?E.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...E,reasoning:me,toolCall:ke,tools:Ee}},m=E=>{if(E.role!=="assistant"||E.variant)return!0;let me=Array.isArray(E.contentParts)&&E.contentParts.length>0,ke=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||me||ke||!!E.stopReason},f=E=>{m(E)&&n({type:"message",message:p(E)})},g=null,x=null,v={current:null},M={current:null},S=null,R="",O=new Map,k=new Map,I=new Map,A=new Map,H=new Map,D={lastId:null,byStep:new Map},N={lastId:null,byCall:new Map},L=E=>{if(E==null)return null;try{return String(E)}catch{return null}},U=E=>{var me,ke,Ee,Re,nt;return L((nt=(Re=(Ee=(ke=(me=E.stepId)!=null?me:E.step_id)!=null?ke:E.step)!=null?Ee:E.parentId)!=null?Re:E.flowStepId)!=null?nt:E.flow_step_id)},V=E=>{var me,ke,Ee,Re,nt,Qe,ut;return L((ut=(Qe=(nt=(Re=(Ee=(ke=(me=E.callId)!=null?me:E.call_id)!=null?ke:E.requestId)!=null?Ee:E.request_id)!=null?Re:E.toolCallId)!=null?nt:E.tool_call_id)!=null?Qe:E.stepId)!=null?ut:E.step_id)},ne=r,Ie=!1,Ue=()=>{if(g)return g;let E,me=S;return!Ie&&ne?(E=ne,Ie=!0):ne&&me?E=`${ne}_${me}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:E,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(g),g},Ae=(E,me)=>{D.lastId=me,E&&D.byStep.set(E,me)},Le=(E,me)=>{var nt;let ke=(nt=E.reasoningId)!=null?nt:E.id,Ee=U(E);if(ke){let Qe=String(ke);return Ae(Ee,Qe),Qe}if(Ee){let Qe=D.byStep.get(Ee);if(Qe)return D.lastId=Qe,Qe}if(D.lastId&&!me)return D.lastId;if(!me)return null;let Re=`reason-${c()}`;return Ae(Ee,Re),Re},_e=E=>{let me=A.get(E);if(me)return me;let ke={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return A.set(E,ke),f(ke),ke},ye=(E,me)=>{N.lastId=me,E&&N.byCall.set(E,me)},De=new Set,ie=new Map,X=new Set,re=new Map,ce=E=>{if(!E)return!1;let me=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},oe=(E,me)=>{var nt;let ke=(nt=E.toolId)!=null?nt:E.id,Ee=V(E);if(ke){let Qe=String(ke);return ye(Ee,Qe),Qe}if(Ee){let Qe=N.byCall.get(Ee);if(Qe)return N.lastId=Qe,Qe}if(N.lastId&&!me)return N.lastId;if(!me)return null;let Re=`tool-${c()}`;return ye(Ee,Re),Re},J=E=>{let me=H.get(E);if(me)return me;let ke={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return H.set(E,ke),f(ke),ke},te=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let me=Number(E);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let ke=Date.parse(E);if(!Number.isNaN(ke))return ke}return Date.now()},ze=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Q=new Map,le=new Map,We=new Map,we=(E,me,ke)=>{var ut;let Ee=We.get(E);Ee||(Ee=[],We.set(E,Ee));let Re=0,nt=Ee.length;for(;Re<nt;){let Rt=Re+nt>>>1;Ee[Rt].seq<me?Re=Rt+1:nt=Rt}((ut=Ee[Re])==null?void 0:ut.seq)===me?Ee[Re]={seq:me,text:ke}:Ee.splice(Re,0,{seq:me,text:ke});let Qe="";for(let Rt=0;Rt<Ee.length;Rt++)Qe+=Ee[Rt].text;return Qe},Ye=(E,me)=>{let ke=ze(me),Ee=le.get(E.id),Re=ty(Ee,ke);E.rawContent=Re;let nt=Q.get(E.id),Qe=K=>{var Me;let ue=(Me=E.content)!=null?Me:"";K.trim()!==""&&(ue.trim().length===0||K.startsWith(ue)||K.trimStart().startsWith(ue.trim()))&&(E.content=K)},ut=()=>{var K;if(nt){let ue=(K=nt.close)==null?void 0:K.call(nt);ue instanceof Promise&&ue.catch(()=>{})}Q.delete(E.id),le.delete(E.id),E.streaming=!1,f(E)};if(!nt){Qe(ke),ut();return}let Rt=ia(Re);if(Rt!==null&&Rt.trim()!==""){Qe(Rt),ut();return}let q=K=>{var xt;let ue=typeof K=="string"?K:(xt=K==null?void 0:K.text)!=null?xt:null;if(ue!==null&&ue.trim()!=="")return ue;let Me=nt.getExtractedText();return Me!==null&&Me.trim()!==""?Me:ke},at;try{at=nt.processChunk(Re)}catch{Qe(ke),ut();return}if(at instanceof Promise){at.then(K=>{Qe(q(K)),ut()}).catch(()=>{Qe(ke),ut()});return}Qe(q(at)),ut()},Ge=null,Oe=(E,me,ke,Ee)=>{var Rt;E.rawContent=me,Q.has(E.id)||Q.set(E.id,this.createStreamParser());let Re=Q.get(E.id),nt=me.trim().startsWith("{")||me.trim().startsWith("[");if(nt&&le.set(E.id,me),Re.__isPlainTextParser===!0){E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E);return}let ut=Re.processChunk(me);if(ut instanceof Promise)ut.then(q=>{var K;let at=typeof q=="string"?q:(K=q==null?void 0:q.text)!=null?K:null;at!==null&&at.trim()!==""?(E.content=at,f(E)):!nt&&!me.trim().startsWith("<")&&(E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E)});else{let q=typeof ut=="string"?ut:(Rt=ut==null?void 0:ut.text)!=null?Rt:null;q!==null&&q.trim()!==""?(E.content=q,f(E)):!nt&&!me.trim().startsWith("<")&&(E.content=Ee!==void 0?me:E.content+ke,le.delete(E.id),Q.delete(E.id),E.rawContent=void 0,f(E))}},de=(E,me)=>{var Rt,q;let ke=me!=null?me:E.content;if(ke==null||ke===""){E.streaming=!1,f(E);return}let Ee=le.get(E.id),Re=Ee!=null?Ee:ze(ke);E.rawContent=Re;let nt=Q.get(E.id),Qe=null,ut=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=ia(Re)),Qe===null)){let at=nt.processChunk(Re);at instanceof Promise?(ut=!0,at.then(K=>{var Me;let ue=typeof K=="string"?K:(Me=K==null?void 0:K.text)!=null?Me:null;ue!==null&&(E.content=ue,E.streaming=!1,Q.delete(E.id),le.delete(E.id),f(E))}).catch(()=>{})):Qe=typeof at=="string"?at:(Rt=at==null?void 0:at.text)!=null?Rt:null}if(!ut){Qe!==null&&Qe.trim()!==""?E.content=Qe:le.has(E.id)||(E.content=ze(ke));let at=Q.get(E.id);if(at){let K=(q=at.close)==null?void 0:q.call(at);K instanceof Promise&&K.catch(()=>{}),Q.delete(E.id)}le.delete(E.id),E.streaming=!1,f(E)}},tt=(E,me,ke)=>{let Ee=k.get(E);if(Ee)return Ee;let Re={id:`nested-${me}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ke?{variant:ke}:{},...ke==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return k.set(E,Re),f(Re),Re},Y=[],pe,Ce=new Map,Ve=0,Pt="agent",Te=null,ge=null,hn=new Map,It=(sn=this.config.iterationDisplay)!=null?sn:"separate";for(pe=()=>{var E,me,ke,Ee,Re,nt,Qe,ut,Rt,q,at,K,ue,Me,xt,Zt,en,mn,Ht,rt,Wt,ct,Gt,Zn,Sn,tn,In,vr,vt,Nn,wr,Br,dr,yt,Lo,Cr,Po,Rn,rs,to,Dr,no,ro,Io,Ro,oo,Ct,On,Fn,An,At,er,tr,_n,so,Nr,ao,$n,Bt,Tn,nr,io,Or,lo,Sr,jn,be,dt,Qt,an,Ar,Fs,Fr,Wo,Tr,_,os,Er,Mr,_r,kr,pr,ss,Ia,Un,qn,ur,mr,Ho,$r,bn,Lr,as,Bo,is,Ra,ls,Wa,cs,ht,_s,rr,Wn,Ha,Ba;for(let co=0;co<Y.length;co++){let ot=Y[co].payloadType,w=Y[co].payload;if(ot==="reasoning_start"){let j=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&$){O.set(j,$),tt(j,$,"reasoning");continue}let G=(E=Le(w,!0))!=null?E:`reason-${c()}`,he=_e(G);he.reasoning=(me=he.reasoning)!=null?me:{id:G,status:"streaming",chunks:[]},he.reasoning.startedAt=(Ee=he.reasoning.startedAt)!=null?Ee:te((ke=w.startedAt)!=null?ke: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",f(he)}else if(ot==="reasoning_delta"){let j=typeof w.id=="string"?w.id:null;if(j&&O.has(j)&&k.has(j)){let $e=k.get(j),Ze=(Qe=(nt=(Re=w.reasoningText)!=null?Re:w.text)!=null?nt:w.delta)!=null?Qe:"";Ze&&w.hidden!==!0&&$e.reasoning&&($e.reasoning.chunks.push(String(Ze)),f($e));continue}let $=(Rt=(ut=Le(w,!1))!=null?ut:Le(w,!0))!=null?Rt:`reason-${c()}`,G=_e($);G.reasoning=(q=G.reasoning)!=null?q:{id:$,status:"streaming",chunks:[]},G.reasoning.startedAt=(K=G.reasoning.startedAt)!=null?K:te((at=w.startedAt)!=null?at:w.timestamp);let he=(xt=(Me=(ue=w.reasoningText)!=null?ue:w.text)!=null?Me:w.delta)!=null?xt:"";if(he&&w.hidden!==!0){let $e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if($e!==void 0){let Ze=we($,$e,String(he));G.reasoning.chunks=[Ze]}else G.reasoning.chunks.push(String(he))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=te((Zt=w.completedAt)!=null?Zt:w.timestamp);let $e=(en=G.reasoning.startedAt)!=null?en:Date.now();G.reasoning.durationMs=Math.max(0,((mn=G.reasoning.completedAt)!=null?mn:Date.now())-$e)}G.streaming=G.reasoning.status!=="complete",f(G)}else if(ot==="reasoning_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&O.has(j)&&k.has(j)){let Ze=k.get(j);if(Ze.reasoning){let Mt=typeof w.text=="string"?w.text:"";Mt&&Ze.reasoning.chunks.length===0&&Ze.reasoning.chunks.push(Mt),Ze.reasoning.status="complete",Ze.streaming=!1,f(Ze)}O.delete(j),k.delete(j);continue}let $=(rt=(Ht=Le(w,!1))!=null?Ht:Le(w,!0))!=null?rt:`reason-${c()}`,G=typeof w.text=="string"?w.text:"";!A.get($)&&(G||w.scope==="loop")&&_e($);let he=A.get($);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),G&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(G),he.reasoning.status="complete",he.reasoning.completedAt=te((Wt=w.completedAt)!=null?Wt:w.timestamp);let Ze=(ct=he.reasoning.startedAt)!=null?ct:Date.now();he.reasoning.durationMs=Math.max(0,((Gt=he.reasoning.completedAt)!=null?Gt:Date.now())-Ze),he.streaming=!1,f(he)}let $e=U(w);$e&&D.byStep.delete($e)}else if(ot==="tool_start"){g&&(g.streaming=!1,f(g),g=null),typeof w.iteration=="number"&&(Ve=w.iteration);let j=(Sn=(Zn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Zn:oe(w,!0))!=null?Sn:`tool-${c()}`,$=(tn=w.toolName)!=null?tn:w.name;if(ce($)){De.add(j);continue}ye(V(w),j);let G=J(j),he=(In=G.toolCall)!=null?In:{id:j,status:"pending"};he.name=$!=null?$:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(vt=he.startedAt)!=null?vt:te((vr=w.startedAt)!=null?vr:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,G.toolCall=he,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),f(G)}else if(ot==="tool_output_delta"){let j=(wr=(Nn=oe(w,!1))!=null?Nn:oe(w,!0))!=null?wr:`tool-${c()}`;if(De.has(j))continue;let $=J(j),G=(Br=$.toolCall)!=null?Br:{id:j,status:"running"};G.startedAt=(yt=G.startedAt)!=null?yt:te((dr=w.startedAt)!=null?dr:w.timestamp);let he=(Po=(Cr=(Lo=w.text)!=null?Lo:w.delta)!=null?Cr:w.message)!=null?Po:"";he&&(G.chunks=(Rn=G.chunks)!=null?Rn:[],G.chunks.push(String(he))),G.status="running",$.toolCall=G,$.streaming=!0;let $e=w.agentContext;($e||w.executionId)&&($.agentMetadata=(Dr=$.agentMetadata)!=null?Dr:{executionId:(rs=$e==null?void 0:$e.executionId)!=null?rs:w.executionId,iteration:(to=$e==null?void 0:$e.iteration)!=null?to:w.iteration}),f($)}else if(ot==="tool_complete"){let j=(ro=(no=oe(w,!1))!=null?no:oe(w,!0))!=null?ro:`tool-${c()}`;if(De.has(j)){De.delete(j);continue}let $=J(j),G=(Io=$.toolCall)!=null?Io:{id:j,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=te((Ro=w.completedAt)!=null?Ro:w.timestamp);let he=(oo=w.duration)!=null?oo:w.executionTime;if(typeof he=="number")G.durationMs=he;else{let Mt=(Ct=G.startedAt)!=null?Ct:Date.now();G.durationMs=Math.max(0,((On=G.completedAt)!=null?On:Date.now())-Mt)}$.toolCall=G,$.streaming=!1;let $e=w.agentContext;($e||w.executionId)&&($.agentMetadata=(At=$.agentMetadata)!=null?At:{executionId:(Fn=$e==null?void 0:$e.executionId)!=null?Fn:w.executionId,iteration:(An=$e==null?void 0:$e.iteration)!=null?An:w.iteration}),f($);let Ze=V(w);Ze&&N.byCall.delete(Ze)}else if(ot==="await"&&w.toolName){let j=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,$=(er=j!=null?j:w.toolId)!=null?er:`local-${c()}`,G=J($),he=w.toolName,$e=w.origin==="webmcp"&&!ho(he)?`webmcp:${he}`:he,Ze=ho($e),Mt=(tr=G.toolCall)!=null?tr:{id:$,status:"pending"};Mt.name=$e,Mt.args=w.parameters,Mt.status=Ze?"running":"complete",Mt.chunks=(_n=Mt.chunks)!=null?_n:[],Mt.startedAt=(ao=Mt.startedAt)!=null?ao:te((Nr=(so=w.startedAt)!=null?so:w.timestamp)!=null?Nr:w.awaitedAt),Ze?(Mt.completedAt=void 0,Mt.duration=void 0,Mt.durationMs=void 0):Mt.completedAt=($n=Mt.completedAt)!=null?$n:Mt.startedAt,G.toolCall=Mt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Tn=w.executionId)!=null?Tn:(Bt=G.agentMetadata)==null?void 0:Bt.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},f(G)}else if(ot==="text_start"){let j=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&$){O.set(j,$);continue}let G=g;G&&(Pt==="flow"?(de(G),Ge=G):(G.streaming=!1,f(G)),g=null),S=typeof w.id=="string"?w.id:S,R=""}else if(ot==="text_delta"){let j=typeof w.id=="string"?w.id:null,$=j?O.get(j):void 0;if(j&&$){let he=typeof w.delta=="string"?w.delta:"",$e=((nr=I.get(j))!=null?nr:"")+he;if(I.set(j,$e),$e.trim()==="")continue;let Ze=tt(j,$);Ze.agentMetadata={...Ze.agentMetadata,executionId:w.executionId,parentToolId:$},Oe(Ze,$e,he,void 0);continue}if(S=typeof w.id=="string"?w.id:S,Pt==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(R+=he,R.trim()==="")continue;let $e=Ue();$e.agentMetadata={executionId:w.executionId,iteration:w.iteration},Oe($e,R,he,void 0),x=$e;continue}let G=Ue();G.content+=(io=w.delta)!=null?io:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Te!=null?Te:void 0,agentName:ge==null?void 0:ge.agentName},x=G,f(G)}else if(ot==="text_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&O.has(j)){let G=k.get(j);G&&de(G),O.delete(j),I.delete(j),k.delete(j);continue}let $=g;$&&(Pt==="flow"?(de($),Ge=$):(((Or=$.content)!=null?Or:"")===""&&typeof w.text=="string"&&($.content=w.text),$.streaming=!1,f($)),g=null),S=null,R=""}else if(ot==="step_complete"){let j=w.stepType,$=w.executionType;if(j==="tool"||$==="context")continue;if(w.success===!1){let G=w.error,he=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((lo=G.message)!=null?lo:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let $e=g;$e&&$e.streaming&&($e.streaming=!1,f($e)),n({type:"status",status:"idle"});continue}{let G=Ge;Ge=null;let he=w.stopReason,$e=(Sr=w.result)==null?void 0:Sr.response;if(G)he&&(G.stopReason=he),$e!=null?Ye(G,$e):G.streaming!==!1&&(Q.delete(G.id),le.delete(G.id),G.streaming=!1,f(G));else{let Ze=$e!=null&&$e!=="";if(Ze||he){let Mt=Ue();he&&(Mt.stopReason=he),Ze?de(Mt,$e):(Mt.streaming=!1,f(Mt))}}continue}}else if(ot==="execution_start")Pt=w.kind==="flow"?"flow":"agent",Pt==="agent"&&(ge={executionId:w.executionId,agentId:(jn=w.agentId)!=null?jn:"virtual",agentName:(be=w.agentName)!=null?be:"",status:"running",currentIteration:0,maxTurns:(dt=w.maxTurns)!=null?dt:1,startedAt:te(w.startedAt)});else if(ot==="turn_start"){let j=typeof w.iteration=="number"?w.iteration:Ve;if(j!==Ve){if(ge&&(ge.currentIteration=j),It==="separate"&&j>1){let $=g;$&&($.streaming=!1,f($),hn.set(j-1,$),g=null)}Ve=j}Te=typeof w.id=="string"?w.id:null,x=null}else if(ot==="tool_input_delta"){let j=(Qt=w.toolCallId)!=null?Qt:N.lastId;if(j){let $=H.get(j);$!=null&&$.toolCall&&($.toolCall.chunks=(an=$.toolCall.chunks)!=null?an:[],$.toolCall.chunks.push((Ar=w.delta)!=null?Ar:""),f($))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let j=w.stopReason,$=g!=null?g:x;if(j&&$!==null){let G=w.id;(!G||((Fs=$.agentMetadata)==null?void 0:Fs.turnId)===G)&&($.stopReason=j,f($))}Te===w.id&&(Te=null)}else if(ot==="media_start"){let j=String(w.id);Ce.set(j,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let j=Ce.get(String(w.id));j&&typeof w.delta=="string"&&j.parts.push(w.delta)}else if(ot==="media_complete"){let j=String(w.id),$=Ce.get(j);Ce.delete(j);let G=(Wo=(Fr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Fr:$==null?void 0:$.mediaType)!=null?Wo:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,$e=typeof w.url=="string"?w.url:$&&$.parts.length>0?$.parts.join(""):void 0,Ze=null;if(he)Ze={type:"media",data:he,mediaType:G};else if($e){let zn=G.toLowerCase();Ze={type:zn==="image"||zn.startsWith("image/")?"image-url":"file-url",url:$e,mediaType:G}}let Mt=(Tr=w.toolCallId)!=null?Tr:$==null?void 0:$.toolCallId,jr=Ze?[Ze]:[],Hn=[];for(let zn of jr){if(!zn||typeof zn!="object")continue;let gn=zn,po=typeof gn.type=="string"?gn.type:void 0,Ur=typeof gn.mediaType=="string"?gn.mediaType.toLowerCase():"",fn=null,Bn="";if(po==="media"){let Vn=typeof gn.data=="string"?gn.data:void 0;if(!Vn)continue;Bn=Ur.length>0?Ur:"application/octet-stream",fn=`data:${Bn};base64,${Vn}`}else if(po==="image-url"){let Vn=typeof gn.url=="string"?gn.url:void 0;if(!Vn)continue;Bn=Ur,fn=Vn}else if(po==="file-url"){let Vn=typeof gn.url=="string"?gn.url:void 0;if(!Vn)continue;Bn=Ur,fn=Vn}else continue;if(fn)if(po==="image-url"||Bn.startsWith("image/"))Hn.push({type:"image",image:fn,...Bn.includes("/")?{mimeType:Bn}:{}});else if(Bn.startsWith("audio/"))Hn.push({type:"audio",audio:fn,mimeType:Bn});else if(Bn.startsWith("video/"))Hn.push({type:"video",video:fn,mimeType:Bn});else{let Vn=Bn||"application/octet-stream";Hn.push({type:"file",data:fn,mimeType:Vn,filename:Zh(Vn)})}}if(Hn.length>0){let zn=c(),gn=Mt,Ur={id:`agent-media-${typeof gn=="string"&&gn.length>0?`${gn}-${zn}`:String(zn)}`,role:"assistant",content:"",contentParts:Hn,createdAt:new Date().toISOString(),streaming:!1,sequence:zn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ve}};f(Ur);let fn=g;fn&&(fn.streaming=!1,f(fn)),g=null,v.current=null}}else if(ot==="execution_complete"){let j=(_=w.kind)!=null?_:Pt;j==="agent"&&ge&&(ge.status=w.success?"complete":"error",ge.completedAt=te(w.completedAt),ge.stopReason=w.stopReason);let $=g;$&&(j==="flow"&&$.streaming!==!1?de($):($.streaming=!1,f($)),g=null),S=null,R="",Ge=null,n({type:"status",status:"idle"})}else if(ot==="execution_error"){let j=typeof w.error=="string"?w.error:(Er=(os=w.error)==null?void 0:os.message)!=null?Er:"Execution error";n({type:"error",error:new Error(j)})}else if(ot!=="ping"){if(ot==="approval_start"){let j=(Mr=w.approvalId)!=null?Mr:`approval-${c()}`,$={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(_r=ge==null?void 0:ge.agentId)!=null?_r:"virtual",executionId:(pr=(kr=w.executionId)!=null?kr:ge==null?void 0:ge.executionId)!=null?pr:"",toolName:(ss=w.toolName)!=null?ss:"",toolType:w.toolType,description:(Un=w.description)!=null?Un:`Execute ${(Ia=w.toolName)!=null?Ia:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f($)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let j=(qn=w.approvalId)!=null?qn:`approval-${c()}`,$={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(ur=ge==null?void 0:ge.agentId)!=null?ur:"virtual",executionId:(Ho=(mr=w.executionId)!=null?mr:ge==null?void 0:ge.executionId)!=null?Ho:"",toolName:($r=w.toolName)!=null?$r:"",toolType:w.toolType,description:(Lr=w.description)!=null?Lr:`Execute ${(bn=w.toolName)!=null?bn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f($)}else if(ot==="approval_complete"){let j=w.approvalId;if(j){let G={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:(as=w.decision)!=null?as:"approved",agentId:(Bo=ge==null?void 0:ge.agentId)!=null?Bo:"virtual",executionId:(Ra=(is=w.executionId)!=null?is:ge==null?void 0:ge.executionId)!=null?Ra:"",toolName:(ls=w.toolName)!=null?ls:"",description:(Wa=w.description)!=null?Wa:"",resolvedAt:Date.now()}};f(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=w.artifactType,$=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:$,artifactType:j,title:G,component:typeof w.component=="string"?w.component:void 0}),re.set($,{markdown:"",title:G}),!X.has($)){X.add($);let he={id:`artifact-ref-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:$,title:G,artifactType:j,status:"streaming"}})};ie.set($,he),f(he)}}else if(ot==="artifact_delta"){let j=String(w.id),$=typeof w.delta=="string"?w.delta:String((cs=w.delta)!=null?cs:"");n({type:"artifact_delta",id:j,artDelta:$});let G=re.get(j);G&&(G.markdown+=$)}else if(ot==="artifact_update"){let j=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:j,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let j=String(w.id);n({type:"artifact_complete",id:j});let $=ie.get(j);if($){$.streaming=!1;try{let G=JSON.parse((ht=$.rawContent)!=null?ht:"{}");if(G.props){G.props.status="complete";let he=re.get(j);he!=null&&he.markdown&&(G.props.markdown=he.markdown)}$.rawContent=JSON.stringify(G)}catch{}re.delete(j),f($),ie.delete(j)}}}else if(ot==="transcript_insert"){let j=w.message;if(!j||typeof j!="object")continue;let $=String((_s=j.id)!=null?_s:`msg-${c()}`),G=j.role,$e={id:$,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:c()};if(f($e),$e.rawContent)try{let Ze=JSON.parse($e.rawContent),Mt=(rr=Ze==null?void 0:Ze.props)==null?void 0:rr.artifactId;typeof Mt=="string"&&X.add(Mt)}catch{}g=null,v.current=null,Q.delete($),le.delete($)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let j=typeof w.error=="string"?w.error:((Wn=w.error)==null?void 0:Wn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(j)});let $=g;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(w.error instanceof Error)j=w.error;else if(ot==="dispatch_error"){let $=(Ha=w.message)!=null?Ha:w.error;$!=null&&$!==""&&(j=new Error(String($)))}else{let $=w.error;typeof $=="string"&&$!==""?j=new Error($):$!=null&&typeof $=="object"&&"message"in $&&(j=new Error(String((Ba=$.message)!=null?Ba:$)))}if(j){n({type:"error",error:j});let $=g;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}}}}}Y.length=0};;){let{done:E,value:me}=await s.read();if(E)break;a+=o.decode(me,{stream:!0});let ke=a.split(`
|
|
10
12
|
|
|
11
13
|
`);a=(xr=ke.pop())!=null?xr:"";for(let Ee of ke){let Re=Ee.split(`
|
|
12
|
-
`),nt="message",Qe="";for(let q of Re)q.startsWith("event:")?nt=q.replace("event:","").trim():q.startsWith("data:")&&(Qe+=q.replace("data:","").trim());if(!Qe)continue;let ut;try{ut=JSON.parse(Qe)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Rt=nt!=="message"?nt:(yn=ut.type)!=null?yn:"message";if((Ke=this.onSSEEvent)==null||Ke.call(this,Rt,ut),this.parseSSEEvent){v.current=g;let q=await this.handleCustomSSEEvent(ut,n,v,f,c,M);if(v.current&&v.current!==g&&(g=v.current),q)continue}Y.push({payloadType:Rt,payload:ut}),pe()}}pe()}};function km(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function As(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Go(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var oi="[Image]";function Lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Im(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Rm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function la(e){return{type:"text",text:e}}function Wm(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 Hm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Bm(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 Dm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qr=[...Dm,...Jh];function Qh(e){return Dm.includes(e)||e.startsWith("image/")}function si(e){return Qh(e.type)}async function Nm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;si(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Om(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 Xh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Fm(e,t){let n=Xh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Ml();var _m=16e3,Yh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ca=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var o,a,i,d;if(this.callLive)return;let t=(o=this.config)==null?void 0:o.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:_m,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,m=new p({sampleRate:_m});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ts(Yh);if(s!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${ny(r)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(g,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,x,s))},x.onmessage=v=>this.handleMessage(v,s),x.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(v.code!==1e3){let M=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,s){let o=t.createMediaStreamSource(n);this.sourceNode=o;let a=t.createScriptProcessor(Zh,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let m=Math.max(-1,Math.min(1,d[p]));c[p]=m<0?m*32768:m*32767}r.send(c.buffer)},o.connect(a),a.connect(t.destination)}handleMessage(t,n){var s,o;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(s=r.text)!=null?s:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(o=r.text)!=null?o:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=ty(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(s=>s(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Jo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function wo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ca(e.runtype);case"browser":if(!Jo.isSupported())throw new Error("Browser speech recognition not supported");return new Jo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ai(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return wo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return wo({type:"runtype",runtype:e.runtype});if(Jo.isSupported())return wo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function da(e){try{return ai(e),!0}catch{return!1}}function Es(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let s=e.find(o=>o.name===r);if(s)return s}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Co=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t.text),o=r.getVoices();if(t.voice){let i=o.find(d=>d.name===t.voice);i&&(s.voice=i)}else o.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(o):Es(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},s.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(s),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Qo=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,s;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(s=this.engine)==null||s.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var s;let r=++this.generation;(s=this.engine)==null||s.stop(),this.set(t,"loading");try{if(!this.engine){let o=await this.resolveEngine();if(r!==this.generation)return;if(!o){this.set(null,"idle");return}this.engine=o}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function kl(e){if(!e)return"";let t=ry(e);return $m(t!==null?t:e)}function ry(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function $m(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,`
|
|
14
|
+
`),nt="message",Qe="";for(let q of Re)q.startsWith("event:")?nt=q.replace("event:","").trim():q.startsWith("data:")&&(Qe+=q.replace("data:","").trim());if(!Qe)continue;let ut;try{ut=JSON.parse(Qe)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Rt=nt!=="message"?nt:(yn=ut.type)!=null?yn:"message";if((Ke=this.onSSEEvent)==null||Ke.call(this,Rt,ut),this.parseSSEEvent){v.current=g;let q=await this.handleCustomSSEEvent(ut,n,v,f,c,M);if(v.current&&v.current!==g&&(g=v.current),q)continue}Y.push({payloadType:Rt,payload:ut}),pe()}}pe()}};function Rm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function As(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Go(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var oi="[Image]";function Wm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Bm(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Dm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function la(e){return{type:"text",text:e}}function Nm(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 Om(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Fm(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 _m=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ny=["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=[..._m,...ny];function ry(e){return _m.includes(e)||e.startsWith("image/")}function si(e){return ry(e.type)}async function $m(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;si(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function jm(e,t=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 oy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Um(e,t){let n=oy(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"}Ml();var qm=16e3,sy=24e3,ay=4096,iy=1380533830;function ly(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===iy?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 ca=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var o,a,i,d;if(this.callLive)return;let t=(o=this.config)==null?void 0:o.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:qm,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,m=new p({sampleRate:qm});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ts(sy);if(s!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${cy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(g,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,x,s))},x.onmessage=v=>this.handleMessage(v,s),x.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(v.code!==1e3){let M=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,s){let o=t.createMediaStreamSource(n);this.sourceNode=o;let a=t.createScriptProcessor(ay,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let m=Math.max(-1,Math.min(1,d[p]));c[p]=m<0?m*32768:m*32767}r.send(c.buffer)},o.connect(a),a.connect(t.destination)}handleMessage(t,n){var s,o;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(s=r.text)!=null?s:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(o=r.text)!=null?o:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=ly(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(s=>s(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Jo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function wo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ca(e.runtype);case"browser":if(!Jo.isSupported())throw new Error("Browser speech recognition not supported");return new Jo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ai(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return wo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return wo({type:"runtype",runtype:e.runtype});if(Jo.isSupported())return wo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function da(e){try{return ai(e),!0}catch{return!1}}function Es(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let s=e.find(o=>o.name===r);if(s)return s}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Co=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t.text),o=r.getVoices();if(t.voice){let i=o.find(d=>d.name===t.voice);i&&(s.voice=i)}else o.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(o):Es(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},s.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(s),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Qo=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,s;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(s=this.engine)==null||s.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var s;let r=++this.generation;(s=this.engine)==null||s.stop(),this.set(t,"loading");try{if(!this.engine){let o=await this.resolveEngine();if(r!==this.generation)return;if(!o){this.set(null,"idle");return}this.engine=o}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function kl(e){if(!e)return"";let t=dy(e);return zm(t!==null?t:e)}function dy(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 zm(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
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
14
|
-
`),t.trim()}var
|
|
16
|
+
`),t.trim()}var Qm=null;var Ll=()=>Qm?Qm():Promise.resolve().then(()=>(Jm(),Gm));var my=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function gy(e,t){return my.some(n=>e[n]!==t[n])}function Xm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
15
17
|
|
|
16
|
-
_Details: ${n.message}_`:r}var pa=e=>({isError:!0,content:[{type:"text",text:e}]}),Gm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Jm=e=>ho(e)||e===yr,Ms=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 Qo(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,s,o,a,i,d,c,p,m;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(ho(f.name)||f.name===yr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((s=t.message.agentMetadata)==null?void 0:s.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(p=this.callbacks).onError)==null||m.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ko(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var s,o,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(s=t.host)!=null?s:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||Ll().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 da((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,s,o,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Co.isSupported()?new Co({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(o=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:o.runtype)==null?void 0:a.agentId,p=this.config.clientToken,m=t.browserFallback!==!1;if(d&&c&&p)return Ll().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:g})=>{let x=new f({host:d,agentId:c,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return m&&n?new g(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(m&&n)return p&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=wo(s);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,c,p,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(o=(s=t.runtype)==null?void 0:s.clientToken)!=null?o:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!iy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new Ko(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:m}=t,g={id:a!=null?a:n==="user"?As():n==="assistant"?Go():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:m=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:s==="user"?As():s==="assistant"?Go():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,c={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(c),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,m,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let s=As(),o=Go(),a={id:s,role:"user",content:r||oi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let M=Km(x,this.config.errorMessage);if(M){let S={id:o,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Go();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let m=Km(c,this.config.errorMessage);if(m){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,m,f,g,x;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===s),i={id:s,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:o};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let S=await v.json().catch(()=>null);throw new Error((f=S==null?void 0:S.error)!=null?f:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);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(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(x=(g=this.callbacks).onError)==null||x.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,f,g,x,v,M,S,R,O,k,I;let r=this.messages.find(A=>A.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let A=(v=t.toolCall)==null?void 0:v.args,H=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(H.length===1){let D=typeof((M=H[0])==null?void 0:M.question)=="string"?H[0].question:"";D&&(a={[D]:n})}}this.markAskUserQuestionResolved(t,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(R=t.toolCall)==null?void 0:R.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof n=="string"?n:Object.entries(n).map(([H,D])=>`${H}: ${Array.isArray(D)?D.join(", "):D}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((H,D)=>{let N=typeof(H==null?void 0:H.question)=="string"?H.question:"";if(!N)return;let L=A[N],U=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${D}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${D}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(s,{[o]:n});if(!A.ok){let H=await A.json().catch(()=>null);throw new Error((O=H==null?void 0:H.error)!=null?O:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let H=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,H||(I=(k=this.callbacks).onError)==null||I.call(k,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,s;if(((r=t.toolCall)==null?void 0:r.name)!==yr)return!1;let n=this.messages.find(o=>o.id===t.id);return((s=(n!=null?n:t).agentMetadata)==null?void 0:s.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now(),o){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...o},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,m;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var I,A,H,D,N,L,U;let g=(I=f.toolCall)==null?void 0:I.name,x=(A=f.toolCall)==null?void 0:A.id;if(!g||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let M=this.markWebMcpToolRunning(f),S=(D=(H=f.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?D:g;if(g===yr)return{dedupeKey:v,resumeKey:S,output:wl(),toolMessage:f,startedAt:M,completedAt:Date.now()};let R=new AbortController;this.webMcpResolveControllers.add(R),s.push(R);let O=this.client.executeWebMcpToolCall(g,(N=f.toolCall)==null?void 0:N.args,R.signal),k;if(!O)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await O}catch(V){let ne=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return ne||(U=(L=this.callbacks).onError)==null||U.call(L,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(f,pa(ne?"Aborted by cancel()":Gm(V)),M),this.webMcpInflightKeys.delete(v),null}return R.signal.aborted?(this.markWebMcpToolComplete(f,pa("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:S,output:k,toolMessage:f,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let f={};for(let x of i)f[x.resumeKey]=x.output;let g=await this.client.resumeFlow(t,f,{signal:o.signal});if(!g.ok){let x=await g.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${g.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===yr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(m=(p=this.callbacks).onError)==null||m.call(p,f instanceof Error?f:new Error(String(f)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,pa("Aborted by cancel()"),x.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of s)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,M,S,R,O,k,I,A,H,D,N;let n=(x=t.agentMetadata)==null?void 0:x.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(M=t.toolCall)==null?void 0:M.id;if(!n){(R=(S=this.callbacks).onError)==null||R.call(S,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!s){let L=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(L)}catch(U){(k=(O=this.callbacks).onError)==null||k.call(O,U instanceof Error?U:new Error(String(U)))}finally{this.webMcpInflightKeys.delete(L)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===yr,p=(I=t.toolCall)==null?void 0:I.args,m=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let L;if(c?L=wl():m?L=await m:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,pa("Aborted by cancel()"),a);return}let U=(H=(A=t.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?H:r;f="resume",await this.resumeWithToolOutput(n,U,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,L,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(L){let U=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(f==="execute"||U||d.aborted)&&this.markWebMcpToolComplete(t,pa(U||d.aborted?"Aborted by cancel()":Gm(L)),a),U||(N=(D=this.callbacks).onError)==null||N.call(D,L instanceof Error?L:new Error(String(L)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=kl(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Es(t)}toggleReadAloud(t){let n=this.messages.find(o=>o.id===t);if(!n||n.role!=="assistant")return;let r=kl(n.content||"");if(!r.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:s==null?void 0:s.voice,rate:s==null?void 0:s.rate,pitch:s==null?void 0:s.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,f,g,x,v,M,S,R,O,k,I,A,H,D;if(o!==r)return s;let a={...s,...n};if(((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=s.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let N=s.approval,L=n.approval;a.approval={...N,...L,executionId:L.executionId||N.executionId,toolName:L.toolName||N.toolName,description:L.description||N.description,toolType:(g=L.toolType)!=null?g:N.toolType,reason:(x=L.reason)!=null?x:N.reason,parameters:(v=L.parameters)!=null?v:N.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(S=n.agentMetadata)==null?void 0:S.executionId,c=(R=n.toolCall)==null?void 0:R.id;if(i&&Jm(i)&&d&&c&&((O=n.agentMetadata)==null?void 0:O.awaitingLocalTool)===!0){let N=`${d}:${c}`,L=this.webMcpInflightKeys.has(N),U=this.webMcpResolvedKeys.has(N),V=(k=s.toolCall)==null?void 0:k.name,ne=((I=s.agentMetadata)==null?void 0:I.executionId)===d&&((A=s.toolCall)==null?void 0:A.id)===c&&V!==void 0&&Jm(V)&&((H=s.toolCall)==null?void 0:H.status)==="complete";(L||U||ne)&&(a.agentMetadata={...(D=a.agentMetadata)!=null?D:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var C=require("lucide"),ly={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},xe=(e,t=24,n="currentColor",r=2)=>{let s=ly[e];return s?cy(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function cy(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}),s}var ci={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function dy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function py(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Xo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ci.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ci.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:ci.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:ci.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Om(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,m);continue}try{let m=await Nm(c),f=si(c)?URL.createObjectURL(c):null,g={id:dy(),file:c,previewUrl:f,contentPart:m};this.attachments.push(g),this.renderPreview(g)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=si(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=py(t.file.type),d=xe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Fm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let s=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=xe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Qm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ua(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];Qm(o)&&Qm(s)?n[r]=ua(o,s):n[r]=s}return n}var Qn="min(440px, calc(100vw - 24px))",di="440px",uy={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Qn,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)"},Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:uy,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xm(e,t){if(!(!e&&!t))return e?t?ua(e,t):e:t}function pi(e){var t,n,r,s,o,a,i,d,c,p,m,f,g,x,v,M,S,R,O,k,I;return e?{...Nt,...e,theme:Xm(Nt.theme,e.theme),darkTheme:Xm(Nt.darkTheme,e.darkTheme),launcher:{...Nt.launcher,...e.launcher,dock:{...(t=Nt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ie,X,re,ce,oe,J,te,ze,Q,le;let A=(ie=Nt.features)==null?void 0:ie.artifacts,H=(X=e.features)==null?void 0:X.artifacts,D=(re=Nt.features)==null?void 0:re.scrollToBottom,N=(ce=e.features)==null?void 0:ce.scrollToBottom,L=(oe=Nt.features)==null?void 0:oe.scrollBehavior,U=(J=e.features)==null?void 0:J.scrollBehavior,V=(te=Nt.features)==null?void 0:te.streamAnimation,ne=(ze=e.features)==null?void 0:ze.streamAnimation,Ie=(Q=Nt.features)==null?void 0:Q.askUserQuestion,Ue=(le=e.features)==null?void 0:le.askUserQuestion,Ae=A===void 0&&H===void 0?void 0:{...A,...H,layout:{...A==null?void 0:A.layout,...H==null?void 0:H.layout}},Le=D===void 0&&N===void 0?void 0:{...D,...N},_e=L===void 0&&U===void 0?void 0:{...L,...U},ye=V===void 0&&ne===void 0?void 0:{...V,...ne},De=Ie===void 0&&Ue===void 0?void 0:{...Ie,...Ue,styles:{...Ie==null?void 0:Ie.styles,...Ue==null?void 0:Ue.styles}};return{...Nt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},..._e!==void 0?{scrollBehavior:_e}:{},...Ae!==void 0?{artifacts:Ae}:{},...ye!==void 0?{streamAnimation:ye}:{},...De!==void 0?{askUserQuestion:De}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Nt.layout,...e.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(m=(p=Nt.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(x=Nt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(S=(M=e.layout)==null?void 0:M.messages)==null?void 0:S.timestamp}},slots:{...(R=Nt.layout)==null?void 0:R.slots,...(O=e.layout)==null?void 0:O.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(k=Nt.markdown)==null?void 0:k.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var Pl={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"}},Il={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"}},Rl={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:Qn,maxWidth:di,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ks(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ks(e,r):r}function ui(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ks(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Wl(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 Ym(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=Ym(o,s):n[r]=s}return n}function my(e,t){return t?Ym(e,t):e}function Ls(e,t={}){var s,o,a,i,d,c,p,m,f,g,x,v,M;let n={palette:Pl,semantic:Il,components:Rl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:my(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=Wl(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(R=>R.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function mi(e){var v,M,S,R,O,k,I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De,ie,X,re,ce,oe,J,te,ze,Q,le,We,we,Ye,Ge,Oe,de,tt,Y,pe,Ce,Ve,Pt,Te,ge,hn,It,sn,xr,yn,Ke,E,me,ke,Ee,Re,nt,Qe,ut,Rt,q,at,K,ue,Me,xt,Zt,en,mn,Ht,rt,Wt,ct,Gt,Zn,Sn,tn,In,vr,vt,Nn,wr,Br,dr,yt,Lo,Cr,Po,Rn,rs,to,Dr,no,ro,Io,Ro,oo,Ct,On,Fn,An,At,er,tr,_n,so,Nr,ao,$n,Bt,Tn,nr,io,Or,lo,Sr,jn;let t=ui(e),n={};for(let[be,dt]of Object.entries(t)){let Qt=be.replace(/\./g,"-");n[`--persona-${Qt}`]=dt.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v: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"]=(S=n["--persona-semantic-colors-accent"])!=null?S:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(R=n["--persona-semantic-colors-surface"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(O=n["--persona-semantic-colors-background"])!=null?O: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"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(H=n["--persona-semantic-colors-text-inverse"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(D=n["--persona-semantic-colors-border"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(N=n["--persona-semantic-colors-divider"])!=null?N:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(L=n["--persona-components-voice-recording-indicator"])!=null?L:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ne=n["--persona-components-voice-speaking-icon"])!=null?ne:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ie=n["--persona-components-approval-requested-background"])!=null?Ie:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ue=n["--persona-components-approval-requested-border"])!=null?Ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ae=n["--persona-components-approval-requested-text"])!=null?Ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(_e=n["--persona-components-approval-approve-background"])!=null?_e:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ye=n["--persona-components-approval-deny-background"])!=null?ye:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(De=n["--persona-components-attachment-image-background"])!=null?De:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ie=n["--persona-components-attachment-image-border"])!=null?ie:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ce=n["--persona-semantic-typography-fontWeight"])!=null?ce:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(oe=n["--persona-semantic-typography-lineHeight"])!=null?oe: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"]=(J=n["--persona-palette-radius-sm"])!=null?J:"0.125rem",n["--persona-radius-md"]=(te=n["--persona-palette-radius-md"])!=null?te:"0.375rem",n["--persona-radius-lg"]=(ze=n["--persona-palette-radius-lg"])!=null?ze:"0.5rem",n["--persona-radius-xl"]=(Q=n["--persona-palette-radius-xl"])!=null?Q:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(we=(We=n["--persona-components-launcher-borderRadius"])!=null?We:n["--persona-palette-radius-full"])!=null?we:"9999px",n["--persona-launcher-bg"]=(Ye=n["--persona-components-launcher-background"])!=null?Ye:n["--persona-primary"],n["--persona-launcher-fg"]=(Ge=n["--persona-components-launcher-foreground"])!=null?Ge:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Oe=n["--persona-components-launcher-border"])!=null?Oe:n["--persona-border"],n["--persona-button-primary-bg"]=(de=n["--persona-components-button-primary-background"])!=null?de:n["--persona-primary"],n["--persona-button-primary-fg"]=(tt=n["--persona-components-button-primary-foreground"])!=null?tt:n["--persona-text-inverse"],n["--persona-button-radius"]=(pe=(Y=n["--persona-components-button-primary-borderRadius"])!=null?Y:n["--persona-palette-radius-full"])!=null?pe:"9999px",n["--persona-panel-radius"]=(Ve=(Ce=n["--persona-components-panel-borderRadius"])!=null?Ce:n["--persona-radius-xl"])!=null?Ve:"0.75rem",n["--persona-panel-border"]=(Pt=n["--persona-components-panel-border"])!=null?Pt:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(ge=(Te=n["--persona-components-panel-shadow"])!=null?Te:n["--persona-palette-shadows-xl"])!=null?ge:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(hn=n["--persona-components-launcher-shadow"])!=null?hn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(sn=(It=n["--persona-components-input-borderRadius"])!=null?It:n["--persona-radius-lg"])!=null?sn:"0.5rem",n["--persona-message-user-radius"]=(yn=(xr=n["--persona-components-message-user-borderRadius"])!=null?xr:n["--persona-radius-lg"])!=null?yn:"0.5rem",n["--persona-message-assistant-radius"]=(E=(Ke=n["--persona-components-message-assistant-borderRadius"])!=null?Ke:n["--persona-radius-lg"])!=null?E:"0.5rem",n["--persona-header-bg"]=(me=n["--persona-components-header-background"])!=null?me:n["--persona-surface"],n["--persona-header-border"]=(ke=n["--persona-components-header-border"])!=null?ke:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ee=n["--persona-components-header-iconBackground"])!=null?Ee:n["--persona-primary"],n["--persona-header-icon-fg"]=(Re=n["--persona-components-header-iconForeground"])!=null?Re:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(nt=n["--persona-components-header-titleForeground"])!=null?nt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Qe=n["--persona-components-header-subtitleForeground"])!=null?Qe:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(ut=n["--persona-components-header-actionIconForeground"])!=null?ut:n["--persona-muted"];let r=(Rt=e.components)==null?void 0:Rt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(at=n["--persona-components-introCard-background"])!=null?at:n["--persona-surface"],n["--persona-intro-card-radius"]=(K=n["--persona-components-introCard-borderRadius"])!=null?K:"1rem",n["--persona-intro-card-padding"]=(ue=n["--persona-components-introCard-padding"])!=null?ue:"1.5rem",n["--persona-intro-card-shadow"]=(xt=(Me=s==null?void 0:s.shadow)!=null?Me:n["--persona-components-introCard-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Zt=n["--persona-components-input-background"])!=null?Zt:n["--persona-surface"],n["--persona-input-placeholder"]=(en=n["--persona-components-input-placeholder"])!=null?en:n["--persona-text-muted"],n["--persona-message-user-bg"]=(mn=n["--persona-components-message-user-background"])!=null?mn:n["--persona-accent"],n["--persona-message-user-text"]=(Ht=n["--persona-components-message-user-text"])!=null?Ht:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(rt=n["--persona-components-message-user-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Wt=n["--persona-components-message-assistant-background"])!=null?Wt: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"]=(Gt=n["--persona-components-message-assistant-border"])!=null?Gt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Zn=n["--persona-components-message-assistant-shadow"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(tn=(Sn=n["--persona-components-scrollToBottom-background"])!=null?Sn:n["--persona-button-primary-bg"])!=null?tn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vr=(In=n["--persona-components-scrollToBottom-foreground"])!=null?In:n["--persona-button-primary-fg"])!=null?vr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(vt=n["--persona-components-scrollToBottom-border"])!=null?vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Nn=n["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",n["--persona-scroll-to-bottom-radius"]=(dr=(Br=(wr=n["--persona-components-scrollToBottom-borderRadius"])!=null?wr:n["--persona-button-radius"])!=null?Br:n["--persona-radius-full"])!=null?dr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Lo=(yt=n["--persona-components-scrollToBottom-shadow"])!=null?yt:n["--persona-palette-shadows-sm"])!=null?Lo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Cr=n["--persona-components-scrollToBottom-padding"])!=null?Cr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Po=n["--persona-components-scrollToBottom-gap"])!=null?Po:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(rs=(Rn=n["--persona-components-scrollToBottom-fontSize"])!=null?Rn:n["--persona-palette-typography-fontSize-sm"])!=null?rs:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(to=n["--persona-components-scrollToBottom-iconSize"])!=null?to:"14px",n["--persona-tool-bubble-shadow"]=(Dr=n["--persona-components-toolBubble-shadow"])!=null?Dr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(no=n["--persona-components-reasoningBubble-shadow"])!=null?no:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(ro=n["--persona-components-composer-shadow"])!=null?ro:"none",n["--persona-md-inline-code-bg"]=(Io=n["--persona-components-markdown-inlineCode-background"])!=null?Io:n["--persona-container"],n["--persona-md-inline-code-color"]=(Ro=n["--persona-components-markdown-inlineCode-foreground"])!=null?Ro:n["--persona-text"],n["--persona-md-link-color"]=(Ct=(oo=n["--persona-components-markdown-link-foreground"])!=null?oo:n["--persona-accent"])!=null?Ct:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(On=n["--persona-components-markdown-codeBlock-background"])!=null?On:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Fn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Fn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(An=n["--persona-components-markdown-codeBlock-textColor"])!=null?An:"inherit",n["--persona-md-table-header-bg"]=(At=n["--persona-components-markdown-table-headerBackground"])!=null?At:n["--persona-container"],n["--persona-md-table-border-color"]=(er=n["--persona-components-markdown-table-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-hr-color"]=(tr=n["--persona-components-markdown-hr-color"])!=null?tr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(_n=n["--persona-components-markdown-blockquote-borderColor"])!=null?_n:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(so=n["--persona-components-markdown-blockquote-background"])!=null?so:"transparent",n["--persona-md-blockquote-text-color"]=(Nr=n["--persona-components-markdown-blockquote-textColor"])!=null?Nr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(ao=n["--persona-components-collapsibleWidget-container"])!=null?ao:n["--persona-surface"],n["--cw-surface"]=($n=n["--persona-components-collapsibleWidget-surface"])!=null?$n:n["--persona-surface"],n["--cw-border"]=(Bt=n["--persona-components-collapsibleWidget-border"])!=null?Bt:n["--persona-border"],n["--persona-message-border"]=(Tn=n["--persona-components-message-border"])!=null?Tn:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let be=x.toolbar;be.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=be.iconHoverColor),be.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=be.iconHoverBackground),be.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=be.iconPadding),be.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=be.iconBorderRadius),be.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=be.iconBorder),be.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=be.toggleGroupGap),be.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=be.toggleBorderRadius),be.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=be.copyBackground),be.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=be.copyBorder),be.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=be.copyColor),be.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=be.copyBorderRadius),be.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=be.copyPadding),be.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=be.copyMenuBackground,n["--persona-dropdown-bg"]=(nr=n["--persona-dropdown-bg"])!=null?nr:be.copyMenuBackground),be.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,n["--persona-dropdown-border"]=(io=n["--persona-dropdown-border"])!=null?io:be.copyMenuBorder),be.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,n["--persona-dropdown-shadow"]=(Or=n["--persona-dropdown-shadow"])!=null?Or:be.copyMenuShadow),be.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(lo=n["--persona-dropdown-radius"])!=null?lo:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Sr=n["--persona-dropdown-item-hover-bg"])!=null?Sr:be.copyMenuItemHoverBackground),be.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=be.iconBackground),be.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=be.toolbarBorder)}if(x!=null&&x.tab){let be=x.tab;be.background&&(n["--persona-artifact-tab-bg"]=be.background),be.activeBackground&&(n["--persona-artifact-tab-active-bg"]=be.activeBackground),be.activeBorder&&(n["--persona-artifact-tab-active-border"]=be.activeBorder),be.borderRadius&&(n["--persona-artifact-tab-radius"]=be.borderRadius),be.textColor&&(n["--persona-artifact-tab-color"]=be.textColor),be.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=be.hoverBackground),be.listBackground&&(n["--persona-artifact-tab-list-bg"]=be.listBackground),be.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=be.listBorderColor),be.listPadding&&(n["--persona-artifact-tab-list-padding"]=be.listPadding)}if(x!=null&&x.pane){let be=x.pane;if(be.toolbarBackground){let dt=(jn=ks(e,be.toolbarBackground))!=null?jn:be.toolbarBackground;n["--persona-artifact-toolbar-bg"]=dt}}return n}var Zm={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var gy={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},eg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ma=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},fy=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ma()},Hl=e=>fy(e),hy=e=>Ls(e),yy=e=>{var n;let t=Ls(void 0,{validate:!1});return Ls({...e,palette:{...t.palette,colors:{...gy.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ps=e=>{let t=Hl(e),n=eg(e==null?void 0:e.theme),r=eg(e==null?void 0:e.darkTheme);return t==="dark"?yy(ua(n!=null?n:{},r!=null?r:{})):hy(n)},by=e=>mi(e),So=(e,t)=>{let n=Ps(t),r=by(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},gi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ma())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ma());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var tg=require("idiomorph"),fi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;tg.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ng=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hi={index:-1,draft:""};function rg(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...hi}}}function og(e,t){var n,r,s,o,a,i,d,c,p,m,f,g,x,v,M,S,R,O,k,I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De,ie,X,re;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(m=e.approval)==null?void 0:m.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(O=(R=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:R.length)!=null?O:0,(H=(A=(I=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?H:"",typeof((D=e.toolCall)==null?void 0:D.args)=="string"?e.toolCall.args.length:(N=e.toolCall)!=null&&N.args?JSON.stringify(e.toolCall.args).length:0,(V=(U=(L=e.reasoning)==null?void 0:L.chunks)==null?void 0:U.length)!=null?V:0,(Ae=(Ue=(Ie=(ne=e.reasoning)==null?void 0:ne.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?Ae:0,(De=(ye=(_e=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:_e[e.reasoning.chunks.length-1])==null?void 0:ye.slice(-32))!=null?De:"",(X=(ie=e.contentParts)==null?void 0:ie.length)!=null?X:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function sg(){return new Map}function ag(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function ig(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function lg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function yi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Yo(e,t){return Xr(e)-e.scrollTop<=t}function bi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function xi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}function cg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function dg(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 pg(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,Ao=Cn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},xy=["pre","code","a","script","style"],vi=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(s=e==null?void 0:e.duration)!=null?s:ga.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:ga.buffer}},mg=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],fa=new Map;for(let e of mg)fa.set(e.name,e);var gg=e=>{fa.set(e.name,e)},fg=e=>{mg.some(t=>t.name===e)||fa.delete(e)},hg=()=>Array.from(fa.keys()),ha=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},wi=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
|
|
17
|
-
`);return o<0?"":e.slice(0,o)}return e},vy=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},wy=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},Bl=/\s/,Cy=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Sy=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Bl.test(o[i])){let c=i;for(;c<o.length&&Bl.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<o.length&&!Bl.test(o[p]);)c.appendChild(vy(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}s.replaceChild(a,e)},Ay=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(wy(r,c,t,n.value)),n.value+=1));s.replaceChild(a,e)},ya=(e,t,n,r)=>{var m,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:xy).map(g=>g.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Cy(d,o)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Sy:Ay;for(let g of i)p(g,n,c);return s.innerHTML},Ci=(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},ba=(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},ug=new WeakMap,Ty=(e,t)=>{var o;if(!e.styles)return;let n=ug.get(t);if(n||(n=new Set,ug.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Dl=new WeakMap,Ey=(e,t)=>{if(!e.onAttach)return;let n=Dl.get(t);if(n||(n=new Map,Dl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},yg=e=>{let t=Dl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Nl=(e,t)=>{Ty(e,t),Ey(e,t)};function Ol(e,t=Cn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var xa=0,To=null;function Fl(e=document){var n;if(xa++,xa===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;To={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,xa=Math.max(0,xa-1),xa===0&&To)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=To.originalOverflow,s.style.position=To.originalPosition,s.style.top=To.originalTop,s.style.width=To.originalWidth,o.scrollTo(0,To.scrollY),To=null}}}var va={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"},Eo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Xn=e=>{var n,r,s,o,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:va.side,width:(s=t==null?void 0:t.width)!=null?s:va.width,animate:(o=t==null?void 0:t.animate)!=null?o:va.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:va.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:va.maxHeight}};var br={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var My="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{var M,S,R,O,k,I;let{showClose:n=!0,wrapperClassName:r=My,buttonSize:s,iconSize:o="28px"}=t,a=(M=e==null?void 0:e.launcher)!=null?M:{},i=(S=s!=null?s:a.closeButtonSize)!=null?S:"32px",d=y("div",r),c=(R=a.closeButtonTooltipText)!=null?R:"Close chat",p=(O=a.closeButtonShowTooltip)!=null?O:!0,m=(k=a.closeButtonIconName)!=null?k:"x",f=(I=a.closeButtonIconText)!=null?I:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Pn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=xe(m,o,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=f,d.appendChild(x),p&&c){let A=null,H=()=>{if(A)return;let N=x.ownerDocument,L=N.body;if(!L)return;A=Wr(N,"div","persona-clear-chat-tooltip"),A.textContent=c;let U=Wr(N,"div");U.className="persona-clear-chat-tooltip-arrow",A.appendChild(U);let V=x.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(Ao),A.style.left=`${V.left+V.width/2}px`,A.style.top=`${V.top-8}px`,A.style.transform="translate(-50%, -100%)",L.appendChild(A)},D=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",H),d.addEventListener("mouseleave",D),x.addEventListener("focus",H),x.addEventListener("blur",D),d._cleanupTooltip=()=>{D(),d.removeEventListener("mouseenter",H),d.removeEventListener("mouseleave",D),x.removeEventListener("focus",H),x.removeEventListener("blur",D)}}return{button:x,wrapper:d}},ky="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ai=(e,t={})=>{var A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e;let{wrapperClassName:n=ky,buttonSize:r,iconSize:s="20px"}=t,a=(H=((A=e==null?void 0:e.launcher)!=null?A:{}).clearChat)!=null?H:{},i=(D=r!=null?r:a.size)!=null?D:"32px",d=(N=a.iconName)!=null?N:"refresh-cw",c=(L=a.iconColor)!=null?L:"",p=(U=a.backgroundColor)!=null?U:"",m=(V=a.borderWidth)!=null?V:"",f=(ne=a.borderColor)!=null?ne:"",g=(Ie=a.borderRadius)!=null?Ie:"",x=(Ue=a.paddingX)!=null?Ue:"",v=(Ae=a.paddingY)!=null?Ae:"",M=(Le=a.tooltipText)!=null?Le:"Clear chat",S=(_e=a.showTooltip)!=null?_e:!0,R=y("div",n),O=!!(m||f),k=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!O&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||Pn.actionIconColor,backgroundColor:p||void 0,border:O?`${m||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),I=xe(d,s,"currentColor",1);if(I&&(I.style.display="block",k.appendChild(I)),R.appendChild(k),S&&M){let ye=null,De=()=>{if(ye)return;let X=k.ownerDocument,re=X.body;if(!re)return;ye=Wr(X,"div","persona-clear-chat-tooltip"),ye.textContent=M;let ce=Wr(X,"div");ce.className="persona-clear-chat-tooltip-arrow",ye.appendChild(ce);let oe=k.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(Ao),ye.style.left=`${oe.left+oe.width/2}px`,ye.style.top=`${oe.top-8}px`,ye.style.transform="translate(-50%, -100%)",re.appendChild(ye)},ie=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};R.addEventListener("mouseenter",De),R.addEventListener("mouseleave",ie),k.addEventListener("focus",De),k.addEventListener("blur",ie),R._cleanupTooltip=()=>{ie(),R.removeEventListener("mouseenter",De),R.removeEventListener("mouseleave",ie),k.removeEventListener("focus",De),k.removeEventListener("blur",ie)}}return{button:k,wrapper:R}};var Pn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Yr=e=>{var I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De;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)))"}}),s=(I=t==null?void 0:t.launcher)!=null?I:{},o=(A=s.headerIconSize)!=null?A:"48px",a=(H=s.closeButtonPlacement)!=null?H:"inline",i=(D=s.headerIconHidden)!=null?D:!1,d=s.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:o,width:o,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let ie=parseFloat(o)||24,X=xe(d,ie*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(L=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?L:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let ie=y("img");ie.src=t.launcher.iconUrl,ie.alt="",ie.className="persona-rounded-xl persona-object-cover",ie.style.height=o,ie.style.width=o,c.replaceChildren(ie)}else c.textContent=(ne=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Et("span",{className:"persona-text-base persona-font-semibold",text:(Ue=(Ie=t==null?void 0:t.launcher)==null?void 0:Ie.title)!=null?Ue:"Chat Assistant",style:{color:Pn.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(Ae=t==null?void 0:t.launcher)==null?void 0:Ae.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});p.append(m,f),i?r.append(p):r.append(c,p);let g=(_e=s.clearChat)!=null?_e:{},x=(ye=g.enabled)!=null?ye:!0,v=(De=g.placement)!=null?De:"inline",M=null,S=null;if(x){let X=Ai(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=X.button,S=X.wrapper,v==="top-right"&&(S.style.right="48px"),v==="inline"&&r.appendChild(S)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:O,wrapper:k}=Si(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:f,closeButton:O,closeButtonWrapper:k,clearChatButton:M,clearChatButtonWrapper:S}},Zo=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Mo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Ao)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let M=xe(g.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let v=document.createElement("span");v.textContent=g.label,x.appendChild(v),x.addEventListener("click",M=>{M.stopPropagation(),p(),n(g.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!r.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:m,destroy:f}}function qt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=xe(t,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function wa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=xe(t,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let m=y("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function Ca(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=y("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=qt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=y("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function c(p){a=p,d()}return{element:o,setSelected:c}}function Ti(e){var g,x;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let m=xe(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,M;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Mo({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),s(v)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var _l=e=>{var r;let t=Yr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function Ly(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=xe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=y("div","persona-relative");d.appendChild(i);let c=Mo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var $l=e=>{var R,O,k,I,A,H,D,N,L;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(R=t==null?void 0:t.launcher)!=null?R:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=Ti({label:(O=a.title)!=null?O:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,p=(k=c.querySelector(".persona-combo-btn-label"))!=null?k:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pn.titleColor,p.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(p),Ly(c,s==null?void 0:s.trailingActions,(A=s==null?void 0:s.onAction)!=null?A:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let V=s.onTitleClick;c.addEventListener("click",ne=>{ne.target.closest("button")||V()}),c.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let U=s==null?void 0:s.titleRowHover;U&&(c.style.borderRadius=(H=U.borderRadius)!=null?H:"10px",c.style.padding=(D=U.padding)!=null?D:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var V,ne;c.style.backgroundColor=(V=U.background)!=null?V:"",c.style.borderColor=(ne=U.border)!=null?ne:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(N=a.closeButtonSize)!=null?N:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=m,g.style.width=m,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Pn.actionIconColor;let x=(L=a.closeButtonIconName)!=null?L:"x",v=xe(x,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let M=y("div");M.style.display="none";let S=y("span");return S.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ei={default:_l,minimal:$l},jl=e=>{var t;return(t=Ei[e])!=null?t:Ei.default},Is=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let m=y("span"),f=y("span"),g=y("button");g.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:m,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=jl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Mi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},ki=e=>{var I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(A=t.useIcon)!=null?A:!1,r=(H=t.iconText)!=null?H:"\u2191",s=t.iconName,o=(D=t.stopIconName)!=null?D:"square",a=(N=t.tooltipText)!=null?N:"Send message",i=(L=t.stopTooltipText)!=null?L:"Stop generating",d=(V=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?V:"Send",c=(Ie=(ne=e==null?void 0:e.copy)==null?void 0:ne.stopButtonLabel)!=null?Ie:"Stop",p=(Ue=t.showTooltip)!=null?Ue:!1,m=(Ae=t.size)!=null?Ae:"40px",f=t.backgroundColor,g=t.textColor,x=y("div","persona-send-button-wrapper"),v=Et("button",{className:Zs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,S=null;if(n){let Le=parseFloat(m)||24,_e=(g==null?void 0:g.trim())||"currentColor";s?(M=xe(s,Le,_e,2),M?v.appendChild(M):v.textContent=r):v.textContent=r,S=xe(o,Le,_e,2)}else v.textContent=d;let R=null;p&&a&&(R=y("div","persona-send-button-tooltip"),R.textContent=a,x.appendChild(R)),v.setAttribute("aria-label",a),x.appendChild(v);let O="send";return{button:v,wrapper:x,setMode:Le=>{if(Le===O)return;O=Le;let _e=Le==="stop"?i:a;if(v.setAttribute("aria-label",_e),R&&(R.textContent=_e),n){if(M&&S){let ye=Le==="stop"?S:M;v.replaceChildren(ye)}}else v.textContent=Le==="stop"?c:d}}},Li=e=>{var R,O,k,I,A,H,D,N,L,U,V,ne;let t=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((O=t.provider)==null?void 0:O.type)==="runtype";if(!(r||s))return null;let a=(I=(k=e==null?void 0:e.sendButton)==null?void 0:k.size)!=null?I:"40px",i=(A=t.iconName)!=null?A:"mic",d=(H=t.iconSize)!=null?H:a,c=parseFloat(d)||24,p=(N=t.backgroundColor)!=null?N:(D=e==null?void 0:e.sendButton)==null?void 0:D.backgroundColor,m=(U=t.iconColor)!=null?U:(L=e==null?void 0:e.sendButton)==null?void 0:L.textColor,f=y("div","persona-send-button-wrapper"),g=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:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=xe(i,c,m||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let M=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((ne=t.showTooltip)!=null?ne:!1)&&M){let Ie=y("div","persona-send-button-tooltip");Ie.textContent=M,f.appendChild(Ie)}return{button:g,wrapper:f}},Pi=e=>{var x,v,M,S,R,O,k,I;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(M=(v=e==null?void 0:e.sendButton)==null?void 0:v.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 s=y("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=((S=t.allowedTypes)!=null?S:Qr).join(","),s.multiple=((R=t.maxFiles)!=null?R:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=(O=t.buttonIconName)!=null?O:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=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 m=xe(o,d,"currentColor",1.5);m?p.appendChild(m):p.textContent="\u{1F4CE}",p.addEventListener("click",A=>{A.preventDefault(),s.click()}),c.appendChild(p);let f=(I=t.buttonTooltipText)!=null?I:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:s,previewsContainer:r}},Ii=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=o;return r},Ri=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Rs=e=>{var x,v,M,S,R,O;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=Ri(),s=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:o,attachAutoResize:a}=Mi(t);a();let i=ki(t),d=Li(t),c=Pi(t),p=Ii(t);c&&(c.previewsContainer.style.gap="8px",s.append(c.previewsContainer,c.input)),s.append(o);let m=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),m.append(f,g),s.append(m),s.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(S=c==null?void 0:c.wrapper)!=null?S:null,attachmentInput:(R=c==null?void 0:c.input)!=null?R:null,attachmentPreviewsContainer:(O=c==null?void 0:c.previewsContainer)!=null?O:null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var bg=()=>{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=xe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),s=y("span","persona-pill-peek__caret"),o=xe("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},xg=e=>{var x,v,M,S,R,O;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ri();r.style.display="none";let s=Ii(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Mi(t);o.style.maxHeight="100px",a();let i=ki(t),d=Li(t),c=Pi(t);c&&c.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"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),c&&p.append(c.input),p.append(m,o,f),c&&n.append(c.previewsContainer),n.append(p,r,s);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(S=c==null?void 0:c.wrapper)!=null?S:null,attachmentInput:(R=c==null?void 0:c.input)!=null?R:null,attachmentPreviewsContainer:(O=c==null?void 0:c.previewsContainer)!=null?O:null,actionsRow:g,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var vg=e=>{var p,m,f,g,x,v,M,S,R,O,k,I,A,H,D,N,L;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=on(e);if(Eo(e)){let U=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},V=y("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(x=U.expandedSize)!=null?x:"anchored",V.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let ne=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let Ie=y("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(S=U.expandedSize)!=null?S:"anchored",Ie.style.zIndex=String((O=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?O:Cn),{wrapper:V,panel:ne,pillRoot:Ie}}if(n){let U=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(V),{wrapper:U,panel:V}}if(!t){let U=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.width)!=null?I:"100%";return U.style.width=ne,V.style.width="100%",U.appendChild(V),{wrapper:U,panel:V}}let s=(A=e==null?void 0:e.launcher)!=null?A:{},o=s.position&&br[s.position]?br[s.position]:br["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((D=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?D:Cn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(L=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?L:e==null?void 0:e.launcherWidth,c=d!=null?d:Qn;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Py=(e,t)=>{var k,I,A,H,D,N,L,U,V;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(A=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.clearChat)==null?void 0:I.enabled)!=null?A:!0,a=null,i=null;if(o){let ne=Ai(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.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"}}),c=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"}});c.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),m=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),f=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,m),g=y("div","persona-flex persona-flex-col persona-gap-3"),x=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);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"}}),S=xg({config:e}),{root:R,textNode:O}=bg();return n.append(d,s,c,M),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:M,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:S.footer,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:R,peekTextNode:O}},wg=(e,t=!0)=>{var M,S,R,O,k,I,A,H,D;if(Eo(e))return Py(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,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=r?Is(e,r,{showClose:t}):Yr({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:(O=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?O:"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."}),c=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{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"),m=(A=e==null?void 0:e.layout)==null?void 0:A.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((H=e==null?void 0:e.copy)==null?void 0:H.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=Rs({config:e}),x=((D=e==null?void 0:e.layout)==null?void 0:D.showFooter)!==!1;s?Zo(n,o,e):(o.header.style.display="none",Zo(n,o,e)),n.append(a);let v=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 x||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Ul=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
18
|
+
_Details: ${n.message}_`:r}var pa=e=>({isError:!0,content:[{type:"text",text:e}]}),Ym=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Zm=e=>ho(e)||e===yr,Ms=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 Qo(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,s,o,a,i,d,c,p,m;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(ho(f.name)||f.name===yr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((s=t.message.agentMetadata)==null?void 0:s.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(p=this.callbacks).onError)==null||m.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ko(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var s,o,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(s=t.host)!=null?s:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||Ll().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 da((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,s,o,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Co.isSupported()?new Co({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(o=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:o.runtype)==null?void 0:a.agentId,p=this.config.clientToken,m=t.browserFallback!==!1;if(d&&c&&p)return Ll().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:g})=>{let x=new f({host:d,agentId:c,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return m&&n?new g(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(m&&n)return p&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=wo(s);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,c,p,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(o=(s=t.runtype)==null?void 0:s.clientToken)!=null?o:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!gy(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 Ko(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:m}=t,g={id:a!=null?a:n==="user"?As():n==="assistant"?Go():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:m=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:s==="user"?As():s==="assistant"?Go():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,c={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(c),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,m,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let s=As(),o=Go(),a={id:s,role:"user",content:r||oi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let M=Xm(x,this.config.errorMessage);if(M){let S={id:o,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Go();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let m=Xm(c,this.config.errorMessage);if(m){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,m,f,g,x;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===s),i={id:s,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:o};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let S=await v.json().catch(()=>null);throw new Error((f=S==null?void 0:S.error)!=null?f:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);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(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(x=(g=this.callbacks).onError)==null||x.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,f,g,x,v,M,S,R,O,k,I;let r=this.messages.find(A=>A.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let A=(v=t.toolCall)==null?void 0:v.args,H=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(H.length===1){let D=typeof((M=H[0])==null?void 0:M.question)=="string"?H[0].question:"";D&&(a={[D]:n})}}this.markAskUserQuestionResolved(t,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(R=t.toolCall)==null?void 0:R.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof n=="string"?n:Object.entries(n).map(([H,D])=>`${H}: ${Array.isArray(D)?D.join(", "):D}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((H,D)=>{let N=typeof(H==null?void 0:H.question)=="string"?H.question:"";if(!N)return;let L=A[N],U=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${D}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${D}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(s,{[o]:n});if(!A.ok){let H=await A.json().catch(()=>null);throw new Error((O=H==null?void 0:H.error)!=null?O:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let H=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,H||(I=(k=this.callbacks).onError)==null||I.call(k,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,s;if(((r=t.toolCall)==null?void 0:r.name)!==yr)return!1;let n=this.messages.find(o=>o.id===t.id);return((s=(n!=null?n:t).agentMetadata)==null?void 0:s.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now(),o){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...o},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,m;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var I,A,H,D,N,L,U;let g=(I=f.toolCall)==null?void 0:I.name,x=(A=f.toolCall)==null?void 0:A.id;if(!g||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let M=this.markWebMcpToolRunning(f),S=(D=(H=f.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?D:g;if(g===yr)return{dedupeKey:v,resumeKey:S,output:wl(),toolMessage:f,startedAt:M,completedAt:Date.now()};let R=new AbortController;this.webMcpResolveControllers.add(R),s.push(R);let O=this.client.executeWebMcpToolCall(g,(N=f.toolCall)==null?void 0:N.args,R.signal),k;if(!O)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await O}catch(V){let ne=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return ne||(U=(L=this.callbacks).onError)==null||U.call(L,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(f,pa(ne?"Aborted by cancel()":Ym(V)),M),this.webMcpInflightKeys.delete(v),null}return R.signal.aborted?(this.markWebMcpToolComplete(f,pa("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:S,output:k,toolMessage:f,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let f={};for(let x of i)f[x.resumeKey]=x.output;let g=await this.client.resumeFlow(t,f,{signal:o.signal});if(!g.ok){let x=await g.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${g.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===yr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(m=(p=this.callbacks).onError)==null||m.call(p,f instanceof Error?f:new Error(String(f)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,pa("Aborted by cancel()"),x.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of s)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,M,S,R,O,k,I,A,H,D,N;let n=(x=t.agentMetadata)==null?void 0:x.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(M=t.toolCall)==null?void 0:M.id;if(!n){(R=(S=this.callbacks).onError)==null||R.call(S,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!s){let L=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(L)}catch(U){(k=(O=this.callbacks).onError)==null||k.call(O,U instanceof Error?U:new Error(String(U)))}finally{this.webMcpInflightKeys.delete(L)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===yr,p=(I=t.toolCall)==null?void 0:I.args,m=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let L;if(c?L=wl():m?L=await m:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,pa("Aborted by cancel()"),a);return}let U=(H=(A=t.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?H:r;f="resume",await this.resumeWithToolOutput(n,U,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,L,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(L){let U=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(f==="execute"||U||d.aborted)&&this.markWebMcpToolComplete(t,pa(U||d.aborted?"Aborted by cancel()":Ym(L)),a),U||(N=(D=this.callbacks).onError)==null||N.call(D,L instanceof Error?L:new Error(String(L)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=kl(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Es(t)}toggleReadAloud(t){let n=this.messages.find(o=>o.id===t);if(!n||n.role!=="assistant")return;let r=kl(n.content||"");if(!r.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:s==null?void 0:s.voice,rate:s==null?void 0:s.rate,pitch:s==null?void 0:s.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,f,g,x,v,M,S,R,O,k,I,A,H,D;if(o!==r)return s;let a={...s,...n};if(((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=s.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let N=s.approval,L=n.approval;a.approval={...N,...L,executionId:L.executionId||N.executionId,toolName:L.toolName||N.toolName,description:L.description||N.description,toolType:(g=L.toolType)!=null?g:N.toolType,reason:(x=L.reason)!=null?x:N.reason,parameters:(v=L.parameters)!=null?v:N.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(S=n.agentMetadata)==null?void 0:S.executionId,c=(R=n.toolCall)==null?void 0:R.id;if(i&&Zm(i)&&d&&c&&((O=n.agentMetadata)==null?void 0:O.awaitingLocalTool)===!0){let N=`${d}:${c}`,L=this.webMcpInflightKeys.has(N),U=this.webMcpResolvedKeys.has(N),V=(k=s.toolCall)==null?void 0:k.name,ne=((I=s.agentMetadata)==null?void 0:I.executionId)===d&&((A=s.toolCall)==null?void 0:A.id)===c&&V!==void 0&&Zm(V)&&((H=s.toolCall)==null?void 0:H.status)==="complete";(L||U||ne)&&(a.agentMetadata={...(D=a.agentMetadata)!=null?D:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var C=require("lucide"),fy={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},xe=(e,t=24,n="currentColor",r=2)=>{let s=fy[e];return s?hy(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function hy(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}),s}var ci={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function yy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function by(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 Xo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ci.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ci.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:ci.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:ci.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=jm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,m);continue}try{let m=await $m(c),f=si(c)?URL.createObjectURL(c):null,g={id:yy(),file:c,previewUrl:f,contentPart:m};this.attachments.push(g),this.renderPreview(g)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=si(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=by(t.file.type),d=xe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Um(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let s=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=xe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var eg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ua(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];eg(o)&&eg(s)?n[r]=ua(o,s):n[r]=s}return n}var Qn="min(440px, calc(100vw - 24px))",di="440px",xy={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:Qn,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)"},Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:xy,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 tg(e,t){if(!(!e&&!t))return e?t?ua(e,t):e:t}function pi(e){var t,n,r,s,o,a,i,d,c,p,m,f,g,x,v,M,S,R,O,k,I;return e?{...Nt,...e,theme:tg(Nt.theme,e.theme),darkTheme:tg(Nt.darkTheme,e.darkTheme),launcher:{...Nt.launcher,...e.launcher,dock:{...(t=Nt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Nt.copy,...e.copy},sendButton:{...Nt.sendButton,...e.sendButton},statusIndicator:{...Nt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ie,X,re,ce,oe,J,te,ze,Q,le;let A=(ie=Nt.features)==null?void 0:ie.artifacts,H=(X=e.features)==null?void 0:X.artifacts,D=(re=Nt.features)==null?void 0:re.scrollToBottom,N=(ce=e.features)==null?void 0:ce.scrollToBottom,L=(oe=Nt.features)==null?void 0:oe.scrollBehavior,U=(J=e.features)==null?void 0:J.scrollBehavior,V=(te=Nt.features)==null?void 0:te.streamAnimation,ne=(ze=e.features)==null?void 0:ze.streamAnimation,Ie=(Q=Nt.features)==null?void 0:Q.askUserQuestion,Ue=(le=e.features)==null?void 0:le.askUserQuestion,Ae=A===void 0&&H===void 0?void 0:{...A,...H,layout:{...A==null?void 0:A.layout,...H==null?void 0:H.layout}},Le=D===void 0&&N===void 0?void 0:{...D,...N},_e=L===void 0&&U===void 0?void 0:{...L,...U},ye=V===void 0&&ne===void 0?void 0:{...V,...ne},De=Ie===void 0&&Ue===void 0?void 0:{...Ie,...Ue,styles:{...Ie==null?void 0:Ie.styles,...Ue==null?void 0:Ue.styles}};return{...Nt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},..._e!==void 0?{scrollBehavior:_e}:{},...Ae!==void 0?{artifacts:Ae}:{},...ye!==void 0?{streamAnimation:ye}:{},...De!==void 0?{askUserQuestion:De}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Nt.layout,...e.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(m=(p=Nt.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(x=Nt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(S=(M=e.layout)==null?void 0:M.messages)==null?void 0:S.timestamp}},slots:{...(R=Nt.layout)==null?void 0:R.slots,...(O=e.layout)==null?void 0:O.slots}},markdown:{...Nt.markdown,...e.markdown,options:{...(k=Nt.markdown)==null?void 0:k.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Nt.messageActions,...e.messageActions}}:Nt}var Pl={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"}},Il={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"}},Rl={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:Qn,maxWidth:di,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ks(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ks(e,r):r}function ui(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ks(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Wl(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 ng(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=ng(o,s):n[r]=s}return n}function vy(e,t){return t?ng(e,t):e}function Ls(e,t={}){var s,o,a,i,d,c,p,m,f,g,x,v,M;let n={palette:Pl,semantic:Il,components:Rl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:vy(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=Wl(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(R=>R.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function mi(e){var v,M,S,R,O,k,I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De,ie,X,re,ce,oe,J,te,ze,Q,le,We,we,Ye,Ge,Oe,de,tt,Y,pe,Ce,Ve,Pt,Te,ge,hn,It,sn,xr,yn,Ke,E,me,ke,Ee,Re,nt,Qe,ut,Rt,q,at,K,ue,Me,xt,Zt,en,mn,Ht,rt,Wt,ct,Gt,Zn,Sn,tn,In,vr,vt,Nn,wr,Br,dr,yt,Lo,Cr,Po,Rn,rs,to,Dr,no,ro,Io,Ro,oo,Ct,On,Fn,An,At,er,tr,_n,so,Nr,ao,$n,Bt,Tn,nr,io,Or,lo,Sr,jn;let t=ui(e),n={};for(let[be,dt]of Object.entries(t)){let Qt=be.replace(/\./g,"-");n[`--persona-${Qt}`]=dt.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v: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"]=(S=n["--persona-semantic-colors-accent"])!=null?S:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(R=n["--persona-semantic-colors-surface"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(O=n["--persona-semantic-colors-background"])!=null?O: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"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(H=n["--persona-semantic-colors-text-inverse"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(D=n["--persona-semantic-colors-border"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(N=n["--persona-semantic-colors-divider"])!=null?N:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(L=n["--persona-components-voice-recording-indicator"])!=null?L:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ne=n["--persona-components-voice-speaking-icon"])!=null?ne:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ie=n["--persona-components-approval-requested-background"])!=null?Ie:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ue=n["--persona-components-approval-requested-border"])!=null?Ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ae=n["--persona-components-approval-requested-text"])!=null?Ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(_e=n["--persona-components-approval-approve-background"])!=null?_e:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ye=n["--persona-components-approval-deny-background"])!=null?ye:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(De=n["--persona-components-attachment-image-background"])!=null?De:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ie=n["--persona-components-attachment-image-border"])!=null?ie:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ce=n["--persona-semantic-typography-fontWeight"])!=null?ce:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(oe=n["--persona-semantic-typography-lineHeight"])!=null?oe: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"]=(J=n["--persona-palette-radius-sm"])!=null?J:"0.125rem",n["--persona-radius-md"]=(te=n["--persona-palette-radius-md"])!=null?te:"0.375rem",n["--persona-radius-lg"]=(ze=n["--persona-palette-radius-lg"])!=null?ze:"0.5rem",n["--persona-radius-xl"]=(Q=n["--persona-palette-radius-xl"])!=null?Q:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(we=(We=n["--persona-components-launcher-borderRadius"])!=null?We:n["--persona-palette-radius-full"])!=null?we:"9999px",n["--persona-launcher-bg"]=(Ye=n["--persona-components-launcher-background"])!=null?Ye:n["--persona-primary"],n["--persona-launcher-fg"]=(Ge=n["--persona-components-launcher-foreground"])!=null?Ge:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Oe=n["--persona-components-launcher-border"])!=null?Oe:n["--persona-border"],n["--persona-button-primary-bg"]=(de=n["--persona-components-button-primary-background"])!=null?de:n["--persona-primary"],n["--persona-button-primary-fg"]=(tt=n["--persona-components-button-primary-foreground"])!=null?tt:n["--persona-text-inverse"],n["--persona-button-radius"]=(pe=(Y=n["--persona-components-button-primary-borderRadius"])!=null?Y:n["--persona-palette-radius-full"])!=null?pe:"9999px",n["--persona-panel-radius"]=(Ve=(Ce=n["--persona-components-panel-borderRadius"])!=null?Ce:n["--persona-radius-xl"])!=null?Ve:"0.75rem",n["--persona-panel-border"]=(Pt=n["--persona-components-panel-border"])!=null?Pt:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(ge=(Te=n["--persona-components-panel-shadow"])!=null?Te:n["--persona-palette-shadows-xl"])!=null?ge:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(hn=n["--persona-components-launcher-shadow"])!=null?hn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(sn=(It=n["--persona-components-input-borderRadius"])!=null?It:n["--persona-radius-lg"])!=null?sn:"0.5rem",n["--persona-message-user-radius"]=(yn=(xr=n["--persona-components-message-user-borderRadius"])!=null?xr:n["--persona-radius-lg"])!=null?yn:"0.5rem",n["--persona-message-assistant-radius"]=(E=(Ke=n["--persona-components-message-assistant-borderRadius"])!=null?Ke:n["--persona-radius-lg"])!=null?E:"0.5rem",n["--persona-header-bg"]=(me=n["--persona-components-header-background"])!=null?me:n["--persona-surface"],n["--persona-header-border"]=(ke=n["--persona-components-header-border"])!=null?ke:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ee=n["--persona-components-header-iconBackground"])!=null?Ee:n["--persona-primary"],n["--persona-header-icon-fg"]=(Re=n["--persona-components-header-iconForeground"])!=null?Re:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(nt=n["--persona-components-header-titleForeground"])!=null?nt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Qe=n["--persona-components-header-subtitleForeground"])!=null?Qe:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(ut=n["--persona-components-header-actionIconForeground"])!=null?ut:n["--persona-muted"];let r=(Rt=e.components)==null?void 0:Rt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(at=n["--persona-components-introCard-background"])!=null?at:n["--persona-surface"],n["--persona-intro-card-radius"]=(K=n["--persona-components-introCard-borderRadius"])!=null?K:"1rem",n["--persona-intro-card-padding"]=(ue=n["--persona-components-introCard-padding"])!=null?ue:"1.5rem",n["--persona-intro-card-shadow"]=(xt=(Me=s==null?void 0:s.shadow)!=null?Me:n["--persona-components-introCard-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Zt=n["--persona-components-input-background"])!=null?Zt:n["--persona-surface"],n["--persona-input-placeholder"]=(en=n["--persona-components-input-placeholder"])!=null?en:n["--persona-text-muted"],n["--persona-message-user-bg"]=(mn=n["--persona-components-message-user-background"])!=null?mn:n["--persona-accent"],n["--persona-message-user-text"]=(Ht=n["--persona-components-message-user-text"])!=null?Ht:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(rt=n["--persona-components-message-user-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Wt=n["--persona-components-message-assistant-background"])!=null?Wt: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"]=(Gt=n["--persona-components-message-assistant-border"])!=null?Gt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Zn=n["--persona-components-message-assistant-shadow"])!=null?Zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(tn=(Sn=n["--persona-components-scrollToBottom-background"])!=null?Sn:n["--persona-button-primary-bg"])!=null?tn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vr=(In=n["--persona-components-scrollToBottom-foreground"])!=null?In:n["--persona-button-primary-fg"])!=null?vr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(vt=n["--persona-components-scrollToBottom-border"])!=null?vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Nn=n["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",n["--persona-scroll-to-bottom-radius"]=(dr=(Br=(wr=n["--persona-components-scrollToBottom-borderRadius"])!=null?wr:n["--persona-button-radius"])!=null?Br:n["--persona-radius-full"])!=null?dr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Lo=(yt=n["--persona-components-scrollToBottom-shadow"])!=null?yt:n["--persona-palette-shadows-sm"])!=null?Lo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Cr=n["--persona-components-scrollToBottom-padding"])!=null?Cr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Po=n["--persona-components-scrollToBottom-gap"])!=null?Po:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(rs=(Rn=n["--persona-components-scrollToBottom-fontSize"])!=null?Rn:n["--persona-palette-typography-fontSize-sm"])!=null?rs:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(to=n["--persona-components-scrollToBottom-iconSize"])!=null?to:"14px",n["--persona-tool-bubble-shadow"]=(Dr=n["--persona-components-toolBubble-shadow"])!=null?Dr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(no=n["--persona-components-reasoningBubble-shadow"])!=null?no:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(ro=n["--persona-components-composer-shadow"])!=null?ro:"none",n["--persona-md-inline-code-bg"]=(Io=n["--persona-components-markdown-inlineCode-background"])!=null?Io:n["--persona-container"],n["--persona-md-inline-code-color"]=(Ro=n["--persona-components-markdown-inlineCode-foreground"])!=null?Ro:n["--persona-text"],n["--persona-md-link-color"]=(Ct=(oo=n["--persona-components-markdown-link-foreground"])!=null?oo:n["--persona-accent"])!=null?Ct:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(On=n["--persona-components-markdown-codeBlock-background"])!=null?On:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Fn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Fn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(An=n["--persona-components-markdown-codeBlock-textColor"])!=null?An:"inherit",n["--persona-md-table-header-bg"]=(At=n["--persona-components-markdown-table-headerBackground"])!=null?At:n["--persona-container"],n["--persona-md-table-border-color"]=(er=n["--persona-components-markdown-table-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-hr-color"]=(tr=n["--persona-components-markdown-hr-color"])!=null?tr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(_n=n["--persona-components-markdown-blockquote-borderColor"])!=null?_n:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(so=n["--persona-components-markdown-blockquote-background"])!=null?so:"transparent",n["--persona-md-blockquote-text-color"]=(Nr=n["--persona-components-markdown-blockquote-textColor"])!=null?Nr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(ao=n["--persona-components-collapsibleWidget-container"])!=null?ao:n["--persona-surface"],n["--cw-surface"]=($n=n["--persona-components-collapsibleWidget-surface"])!=null?$n:n["--persona-surface"],n["--cw-border"]=(Bt=n["--persona-components-collapsibleWidget-border"])!=null?Bt:n["--persona-border"],n["--persona-message-border"]=(Tn=n["--persona-components-message-border"])!=null?Tn:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let be=x.toolbar;be.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=be.iconHoverColor),be.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=be.iconHoverBackground),be.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=be.iconPadding),be.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=be.iconBorderRadius),be.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=be.iconBorder),be.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=be.toggleGroupGap),be.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=be.toggleBorderRadius),be.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=be.copyBackground),be.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=be.copyBorder),be.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=be.copyColor),be.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=be.copyBorderRadius),be.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=be.copyPadding),be.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=be.copyMenuBackground,n["--persona-dropdown-bg"]=(nr=n["--persona-dropdown-bg"])!=null?nr:be.copyMenuBackground),be.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,n["--persona-dropdown-border"]=(io=n["--persona-dropdown-border"])!=null?io:be.copyMenuBorder),be.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,n["--persona-dropdown-shadow"]=(Or=n["--persona-dropdown-shadow"])!=null?Or:be.copyMenuShadow),be.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(lo=n["--persona-dropdown-radius"])!=null?lo:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Sr=n["--persona-dropdown-item-hover-bg"])!=null?Sr:be.copyMenuItemHoverBackground),be.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=be.iconBackground),be.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=be.toolbarBorder)}if(x!=null&&x.tab){let be=x.tab;be.background&&(n["--persona-artifact-tab-bg"]=be.background),be.activeBackground&&(n["--persona-artifact-tab-active-bg"]=be.activeBackground),be.activeBorder&&(n["--persona-artifact-tab-active-border"]=be.activeBorder),be.borderRadius&&(n["--persona-artifact-tab-radius"]=be.borderRadius),be.textColor&&(n["--persona-artifact-tab-color"]=be.textColor),be.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=be.hoverBackground),be.listBackground&&(n["--persona-artifact-tab-list-bg"]=be.listBackground),be.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=be.listBorderColor),be.listPadding&&(n["--persona-artifact-tab-list-padding"]=be.listPadding)}if(x!=null&&x.pane){let be=x.pane;if(be.toolbarBackground){let dt=(jn=ks(e,be.toolbarBackground))!=null?jn:be.toolbarBackground;n["--persona-artifact-toolbar-bg"]=dt}}return n}var rg={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 wy={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"}}},og=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ma=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Cy=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ma()},Hl=e=>Cy(e),Sy=e=>Ls(e),Ay=e=>{var n;let t=Ls(void 0,{validate:!1});return Ls({...e,palette:{...t.palette,colors:{...wy.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ps=e=>{let t=Hl(e),n=og(e==null?void 0:e.theme),r=og(e==null?void 0:e.darkTheme);return t==="dark"?Ay(ua(n!=null?n:{},r!=null?r:{})):Sy(n)},Ty=e=>mi(e),So=(e,t)=>{let n=Ps(t),r=Ty(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},gi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ma())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ma());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var sg=require("idiomorph"),fi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;sg.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ag=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hi={index:-1,draft:""};function ig(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...hi}}}function lg(e,t){var n,r,s,o,a,i,d,c,p,m,f,g,x,v,M,S,R,O,k,I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De,ie,X,re;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(m=e.approval)==null?void 0:m.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(O=(R=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:R.length)!=null?O:0,(H=(A=(I=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:I[e.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?H:"",typeof((D=e.toolCall)==null?void 0:D.args)=="string"?e.toolCall.args.length:(N=e.toolCall)!=null&&N.args?JSON.stringify(e.toolCall.args).length:0,(V=(U=(L=e.reasoning)==null?void 0:L.chunks)==null?void 0:U.length)!=null?V:0,(Ae=(Ue=(Ie=(ne=e.reasoning)==null?void 0:ne.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?Ae:0,(De=(ye=(_e=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:_e[e.reasoning.chunks.length-1])==null?void 0:ye.slice(-32))!=null?De:"",(X=(ie=e.contentParts)==null?void 0:ie.length)!=null?X:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function cg(){return new Map}function dg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function pg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function ug(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function yi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Yo(e,t){return Xr(e)-e.scrollTop<=t}function bi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function xi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}function mg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function gg(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 fg(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,Ao=Cn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ey=["pre","code","a","script","style"],vi=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(s=e==null?void 0:e.duration)!=null?s:ga.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:ga.buffer}},yg=[{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"}],fa=new Map;for(let e of yg)fa.set(e.name,e);var bg=e=>{fa.set(e.name,e)},xg=e=>{yg.some(t=>t.name===e)||fa.delete(e)},vg=()=>Array.from(fa.keys()),ha=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},wi=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
|
|
19
|
+
`);return o<0?"":e.slice(0,o)}return e},My=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},ky=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},Bl=/\s/,Ly=(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},Py=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Bl.test(o[i])){let c=i;for(;c<o.length&&Bl.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<o.length&&!Bl.test(o[p]);)c.appendChild(My(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}s.replaceChild(a,e)},Iy=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(ky(r,c,t,n.value)),n.value+=1));s.replaceChild(a,e)},ya=(e,t,n,r)=>{var m,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:Ey).map(g=>g.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Ly(d,o)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Py:Iy;for(let g of i)p(g,n,c);return s.innerHTML},Ci=(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},ba=(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},hg=new WeakMap,Ry=(e,t)=>{var o;if(!e.styles)return;let n=hg.get(t);if(n||(n=new Set,hg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Dl=new WeakMap,Wy=(e,t)=>{if(!e.onAttach)return;let n=Dl.get(t);if(n||(n=new Map,Dl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},wg=e=>{let t=Dl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Nl=(e,t)=>{Ry(e,t),Wy(e,t)};function Ol(e,t=Cn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var xa=0,To=null;function Fl(e=document){var n;if(xa++,xa===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;To={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,xa=Math.max(0,xa-1),xa===0&&To)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=To.originalOverflow,s.style.position=To.originalPosition,s.style.top=To.originalTop,s.style.width=To.originalWidth,o.scrollTo(0,To.scrollY),To=null}}}var va={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"},Eo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Xn=e=>{var n,r,s,o,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:va.side,width:(s=t==null?void 0:t.width)!=null?s:va.width,animate:(o=t==null?void 0:t.animate)!=null?o:va.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:va.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:va.maxHeight}};var br={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Hy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{var M,S,R,O,k,I;let{showClose:n=!0,wrapperClassName:r=Hy,buttonSize:s,iconSize:o="28px"}=t,a=(M=e==null?void 0:e.launcher)!=null?M:{},i=(S=s!=null?s:a.closeButtonSize)!=null?S:"32px",d=y("div",r),c=(R=a.closeButtonTooltipText)!=null?R:"Close chat",p=(O=a.closeButtonShowTooltip)!=null?O:!0,m=(k=a.closeButtonIconName)!=null?k:"x",f=(I=a.closeButtonIconText)!=null?I:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Pn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=xe(m,o,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=f,d.appendChild(x),p&&c){let A=null,H=()=>{if(A)return;let N=x.ownerDocument,L=N.body;if(!L)return;A=Wr(N,"div","persona-clear-chat-tooltip"),A.textContent=c;let U=Wr(N,"div");U.className="persona-clear-chat-tooltip-arrow",A.appendChild(U);let V=x.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(Ao),A.style.left=`${V.left+V.width/2}px`,A.style.top=`${V.top-8}px`,A.style.transform="translate(-50%, -100%)",L.appendChild(A)},D=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",H),d.addEventListener("mouseleave",D),x.addEventListener("focus",H),x.addEventListener("blur",D),d._cleanupTooltip=()=>{D(),d.removeEventListener("mouseenter",H),d.removeEventListener("mouseleave",D),x.removeEventListener("focus",H),x.removeEventListener("blur",D)}}return{button:x,wrapper:d}},By="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ai=(e,t={})=>{var A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e;let{wrapperClassName:n=By,buttonSize:r,iconSize:s="20px"}=t,a=(H=((A=e==null?void 0:e.launcher)!=null?A:{}).clearChat)!=null?H:{},i=(D=r!=null?r:a.size)!=null?D:"32px",d=(N=a.iconName)!=null?N:"refresh-cw",c=(L=a.iconColor)!=null?L:"",p=(U=a.backgroundColor)!=null?U:"",m=(V=a.borderWidth)!=null?V:"",f=(ne=a.borderColor)!=null?ne:"",g=(Ie=a.borderRadius)!=null?Ie:"",x=(Ue=a.paddingX)!=null?Ue:"",v=(Ae=a.paddingY)!=null?Ae:"",M=(Le=a.tooltipText)!=null?Le:"Clear chat",S=(_e=a.showTooltip)!=null?_e:!0,R=y("div",n),O=!!(m||f),k=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!O&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||Pn.actionIconColor,backgroundColor:p||void 0,border:O?`${m||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),I=xe(d,s,"currentColor",1);if(I&&(I.style.display="block",k.appendChild(I)),R.appendChild(k),S&&M){let ye=null,De=()=>{if(ye)return;let X=k.ownerDocument,re=X.body;if(!re)return;ye=Wr(X,"div","persona-clear-chat-tooltip"),ye.textContent=M;let ce=Wr(X,"div");ce.className="persona-clear-chat-tooltip-arrow",ye.appendChild(ce);let oe=k.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(Ao),ye.style.left=`${oe.left+oe.width/2}px`,ye.style.top=`${oe.top-8}px`,ye.style.transform="translate(-50%, -100%)",re.appendChild(ye)},ie=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};R.addEventListener("mouseenter",De),R.addEventListener("mouseleave",ie),k.addEventListener("focus",De),k.addEventListener("blur",ie),R._cleanupTooltip=()=>{ie(),R.removeEventListener("mouseenter",De),R.removeEventListener("mouseleave",ie),k.removeEventListener("focus",De),k.removeEventListener("blur",ie)}}return{button:k,wrapper:R}};var Pn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Yr=e=>{var I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De;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)))"}}),s=(I=t==null?void 0:t.launcher)!=null?I:{},o=(A=s.headerIconSize)!=null?A:"48px",a=(H=s.closeButtonPlacement)!=null?H:"inline",i=(D=s.headerIconHidden)!=null?D:!1,d=s.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:o,width:o,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let ie=parseFloat(o)||24,X=xe(d,ie*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(L=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?L:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let ie=y("img");ie.src=t.launcher.iconUrl,ie.alt="",ie.className="persona-rounded-xl persona-object-cover",ie.style.height=o,ie.style.width=o,c.replaceChildren(ie)}else c.textContent=(ne=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Et("span",{className:"persona-text-base persona-font-semibold",text:(Ue=(Ie=t==null?void 0:t.launcher)==null?void 0:Ie.title)!=null?Ue:"Chat Assistant",style:{color:Pn.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(Ae=t==null?void 0:t.launcher)==null?void 0:Ae.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});p.append(m,f),i?r.append(p):r.append(c,p);let g=(_e=s.clearChat)!=null?_e:{},x=(ye=g.enabled)!=null?ye:!0,v=(De=g.placement)!=null?De:"inline",M=null,S=null;if(x){let X=Ai(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=X.button,S=X.wrapper,v==="top-right"&&(S.style.right="48px"),v==="inline"&&r.appendChild(S)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:O,wrapper:k}=Si(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:f,closeButton:O,closeButtonWrapper:k,clearChatButton:M,clearChatButtonWrapper:S}},Zo=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Mo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Ao)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let M=xe(g.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let v=document.createElement("span");v.textContent=g.label,x.appendChild(v),x.addEventListener("click",M=>{M.stopPropagation(),p(),n(g.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!r.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:m,destroy:f}}function qt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=xe(t,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function wa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=xe(t,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let m=y("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function Ca(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=y("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=qt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=y("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function c(p){a=p,d()}return{element:o,setSelected:c}}function Ti(e){var g,x;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let m=xe(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,M;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Mo({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),s(v)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var _l=e=>{var r;let t=Yr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function Dy(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=xe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=y("div","persona-relative");d.appendChild(i);let c=Mo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var $l=e=>{var R,O,k,I,A,H,D,N,L;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(R=t==null?void 0:t.launcher)!=null?R:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=Ti({label:(O=a.title)!=null?O:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,p=(k=c.querySelector(".persona-combo-btn-label"))!=null?k:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pn.titleColor,p.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(p),Dy(c,s==null?void 0:s.trailingActions,(A=s==null?void 0:s.onAction)!=null?A:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let V=s.onTitleClick;c.addEventListener("click",ne=>{ne.target.closest("button")||V()}),c.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let U=s==null?void 0:s.titleRowHover;U&&(c.style.borderRadius=(H=U.borderRadius)!=null?H:"10px",c.style.padding=(D=U.padding)!=null?D:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var V,ne;c.style.backgroundColor=(V=U.background)!=null?V:"",c.style.borderColor=(ne=U.border)!=null?ne:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(N=a.closeButtonSize)!=null?N:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=m,g.style.width=m,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Pn.actionIconColor;let x=(L=a.closeButtonIconName)!=null?L:"x",v=xe(x,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let M=y("div");M.style.display="none";let S=y("span");return S.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ei={default:_l,minimal:$l},jl=e=>{var t;return(t=Ei[e])!=null?t:Ei.default},Is=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let m=y("span"),f=y("span"),g=y("button");g.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:m,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=jl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Mi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},ki=e=>{var I,A,H,D,N,L,U,V,ne,Ie,Ue,Ae;let t=(I=e==null?void 0:e.sendButton)!=null?I:{},n=(A=t.useIcon)!=null?A:!1,r=(H=t.iconText)!=null?H:"\u2191",s=t.iconName,o=(D=t.stopIconName)!=null?D:"square",a=(N=t.tooltipText)!=null?N:"Send message",i=(L=t.stopTooltipText)!=null?L:"Stop generating",d=(V=(U=e==null?void 0:e.copy)==null?void 0:U.sendButtonLabel)!=null?V:"Send",c=(Ie=(ne=e==null?void 0:e.copy)==null?void 0:ne.stopButtonLabel)!=null?Ie:"Stop",p=(Ue=t.showTooltip)!=null?Ue:!1,m=(Ae=t.size)!=null?Ae:"40px",f=t.backgroundColor,g=t.textColor,x=y("div","persona-send-button-wrapper"),v=Et("button",{className:Zs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,S=null;if(n){let Le=parseFloat(m)||24,_e=(g==null?void 0:g.trim())||"currentColor";s?(M=xe(s,Le,_e,2),M?v.appendChild(M):v.textContent=r):v.textContent=r,S=xe(o,Le,_e,2)}else v.textContent=d;let R=null;p&&a&&(R=y("div","persona-send-button-tooltip"),R.textContent=a,x.appendChild(R)),v.setAttribute("aria-label",a),x.appendChild(v);let O="send";return{button:v,wrapper:x,setMode:Le=>{if(Le===O)return;O=Le;let _e=Le==="stop"?i:a;if(v.setAttribute("aria-label",_e),R&&(R.textContent=_e),n){if(M&&S){let ye=Le==="stop"?S:M;v.replaceChildren(ye)}}else v.textContent=Le==="stop"?c:d}}},Li=e=>{var R,O,k,I,A,H,D,N,L,U,V,ne;let t=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((O=t.provider)==null?void 0:O.type)==="runtype";if(!(r||s))return null;let a=(I=(k=e==null?void 0:e.sendButton)==null?void 0:k.size)!=null?I:"40px",i=(A=t.iconName)!=null?A:"mic",d=(H=t.iconSize)!=null?H:a,c=parseFloat(d)||24,p=(N=t.backgroundColor)!=null?N:(D=e==null?void 0:e.sendButton)==null?void 0:D.backgroundColor,m=(U=t.iconColor)!=null?U:(L=e==null?void 0:e.sendButton)==null?void 0:L.textColor,f=y("div","persona-send-button-wrapper"),g=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:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=xe(i,c,m||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let M=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((ne=t.showTooltip)!=null?ne:!1)&&M){let Ie=y("div","persona-send-button-tooltip");Ie.textContent=M,f.appendChild(Ie)}return{button:g,wrapper:f}},Pi=e=>{var x,v,M,S,R,O,k,I;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(M=(v=e==null?void 0:e.sendButton)==null?void 0:v.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 s=y("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=((S=t.allowedTypes)!=null?S:Qr).join(","),s.multiple=((R=t.maxFiles)!=null?R:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=(O=t.buttonIconName)!=null?O:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=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 m=xe(o,d,"currentColor",1.5);m?p.appendChild(m):p.textContent="\u{1F4CE}",p.addEventListener("click",A=>{A.preventDefault(),s.click()}),c.appendChild(p);let f=(I=t.buttonTooltipText)!=null?I:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:s,previewsContainer:r}},Ii=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=o;return r},Ri=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Rs=e=>{var x,v,M,S,R,O;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=Ri(),s=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:o,attachAutoResize:a}=Mi(t);a();let i=ki(t),d=Li(t),c=Pi(t),p=Ii(t);c&&(c.previewsContainer.style.gap="8px",s.append(c.previewsContainer,c.input)),s.append(o);let m=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),m.append(f,g),s.append(m),s.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(S=c==null?void 0:c.wrapper)!=null?S:null,attachmentInput:(R=c==null?void 0:c.input)!=null?R:null,attachmentPreviewsContainer:(O=c==null?void 0:c.previewsContainer)!=null?O:null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Cg=()=>{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=xe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),s=y("span","persona-pill-peek__caret"),o=xe("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Sg=e=>{var x,v,M,S,R,O;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ri();r.style.display="none";let s=Ii(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Mi(t);o.style.maxHeight="100px",a();let i=ki(t),d=Li(t),c=Pi(t);c&&c.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"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),c&&p.append(c.input),p.append(m,o,f),c&&n.append(c.previewsContainer),n.append(p,r,s);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(S=c==null?void 0:c.wrapper)!=null?S:null,attachmentInput:(R=c==null?void 0:c.input)!=null?R:null,attachmentPreviewsContainer:(O=c==null?void 0:c.previewsContainer)!=null?O:null,actionsRow:g,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var Ag=e=>{var p,m,f,g,x,v,M,S,R,O,k,I,A,H,D,N,L;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=on(e);if(Eo(e)){let U=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},V=y("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(x=U.expandedSize)!=null?x:"anchored",V.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let ne=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let Ie=y("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(S=U.expandedSize)!=null?S:"anchored",Ie.style.zIndex=String((O=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?O:Cn),{wrapper:V,panel:ne,pillRoot:Ie}}if(n){let U=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(V),{wrapper:U,panel:V}}if(!t){let U=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.width)!=null?I:"100%";return U.style.width=ne,V.style.width="100%",U.appendChild(V),{wrapper:U,panel:V}}let s=(A=e==null?void 0:e.launcher)!=null?A:{},o=s.position&&br[s.position]?br[s.position]:br["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((D=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?D:Cn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(L=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?L:e==null?void 0:e.launcherWidth,c=d!=null?d:Qn;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Ny=(e,t)=>{var k,I,A,H,D,N,L,U,V;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(A=(I=(k=e==null?void 0:e.launcher)==null?void 0:k.clearChat)==null?void 0:I.enabled)!=null?A:!0,a=null,i=null;if(o){let ne=Ai(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.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"}}),c=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"}});c.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),m=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),f=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,m),g=y("div","persona-flex persona-flex-col persona-gap-3"),x=(U=e==null?void 0:e.layout)==null?void 0:U.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);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"}}),S=Sg({config:e}),{root:R,textNode:O}=Cg();return n.append(d,s,c,M),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:M,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:S.footer,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:R,peekTextNode:O}},Tg=(e,t=!0)=>{var M,S,R,O,k,I,A,H,D;if(Eo(e))return Ny(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,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=r?Is(e,r,{showClose:t}):Yr({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:(O=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?O:"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."}),c=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{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"),m=(A=e==null?void 0:e.layout)==null?void 0:A.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((H=e==null?void 0:e.copy)==null?void 0:H.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=Rs({config:e}),x=((D=e==null?void 0:e.layout)==null?void 0:D.showFooter)!==!1;s?Zo(n,o,e):(o.header.style.display="none",Zo(n,o,e)),n.append(a);let v=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 x||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Ul=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
18
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>
|
|
19
21
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
20
22
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -22,14 +24,14 @@ _Details: ${n.message}_`:r}var pa=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
22
24
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
23
25
|
</span>
|
|
24
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>
|
|
25
|
-
`,n.addEventListener("click",t);let r=o=>{var O,k,I,A,H,D,N,L,U,V,ne,Ie,Ue;let a=(O=o.launcher)!=null?O:{},i=on(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Ae=(k=a.title)!=null?k:"Chat Assistant";d.textContent=Ae,d.setAttribute("title",Ae)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let Ae=(I=a.subtitle)!=null?I:"Here to help you get answers fast";c.textContent=Ae,c.setAttribute("title",Ae)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let Ae=(A=a.agentIconSize)!=null?A:"40px";if(m.style.height=Ae,m.style.width=Ae,m.innerHTML="",a.agentIconName){let Le=parseFloat(Ae)||24,_e=xe(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);_e?(m.appendChild(_e),m.style.display=""):(m.textContent=(H=a.agentIconText)!=null?H:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",m.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let Ae=(N=a.agentIconSize)!=null?N:"40px";f.style.height=Ae,f.style.width=Ae,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Ae=(L=a.callToActionIconSize)!=null?L:"32px";g.style.height=Ae,g.style.width=Ae,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let _e=parseFloat(Ae)||24,ye=Math.max(_e-Le,8),De=xe(a.callToActionIconName,ye,"currentColor",2);De?g.appendChild(De):g.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else g.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let x=a.position&&br[a.position]?br[a.position]:br["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${v} ${x}`,i||(n.style.zIndex=String((ne=a.zIndex)!=null?ne:Cn));let S="1px solid var(--persona-border, #e5e7eb)",R="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=(Ie=a.border)!=null?Ie:S,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,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="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var Cg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:s}=vg(e),o=wg(e,t),a={wrapper:n,panel:r,pillRoot:s},i={container:o.container,body:o.body,messagesWrapper:o.messagesWrapper,composerOverlay:o.composerOverlay,introTitle:o.introTitle,introSubtitle:o.introSubtitle},d={element:o.header,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper},c={footer:o.footer,form:o.composerForm,textarea:o.textarea,sendButton:o.sendButton,sendButtonWrapper:o.sendButtonWrapper,micButton:o.micButton,micButtonWrapper:o.micButtonWrapper,statusText:o.statusText,suggestions:o.suggestions,attachmentButton:o.attachmentButton,attachmentButtonWrapper:o.attachmentButtonWrapper,attachmentInput:o.attachmentInput,attachmentPreviewsContainer:o.attachmentPreviewsContainer,actionsRow:o.actionsRow,leftActions:o.leftActions,rightActions:o.rightActions,setSendButtonMode:o.setSendButtonMode,peekBanner:o.peekBanner,peekTextNode:o.peekTextNode};return{shell:a,panelElements:o,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},ql=({config:e,plugins:t,onToggle:n})=>{let r=t.find(o=>o.renderLauncher);if(r!=null&&r.renderLauncher){let o=r.renderLauncher({config:e,defaultRenderer:()=>Ul(e,n).element,onToggle:n});if(o)return{instance:null,element:o}}let s=Ul(e,n);return{instance:s,element:s.element}};var Iy=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Ry=(e,t)=>{if(!e)return null;let n=Iy(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Wy=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Hy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},zl=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(":"))},Vl=320,Ag=320,By=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Dy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ny=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Oy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Fy=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Vl}px`,c.style.maxHeight=`${Ag}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Hy(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},_y=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!zl(r.audio))return;let s=y("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Vl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},$y=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!zl(r.video))return;let s=y("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Vl}px`,s.style.maxHeight=`${Ag}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!zl(r.data))return;let s=y("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},es=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},Kl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:es};if(t){let s=t(r);if(s!==null)return s}return es()},Uy=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=y("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Sg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?r.textContent=t.format(s):r.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},qy=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Gl=(e,t,n)=>{var x,v,M,S,R,O,k;let r=(x=t.showCopy)!=null?x:!0,s=(v=t.showUpvote)!=null?v:!0,o=(M=t.showDownvote)!=null?M:!0,a=(S=t.showReadAloud)!=null?S:!1;if(!r&&!s&&!o&&!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=(R=t.visibility)!=null?R:"hover",d=(O=t.align)!=null?O:"right",c=(k=t.layout)!=null?k:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(I,A,H)=>{let D=qt({icon:I,label:A,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",H),D};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),s&&f.appendChild(g("thumbs-up","Upvote","upvote")),o&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Ws=(e,t,n,r,s,o)=>{var ie,X,re,ce,oe,J,te,ze,Q,le,We,we,Ye,Ge,Oe,de,tt;let a=n!=null?n:{},i=(ie=a.layout)!=null?ie:"bubble",d=a.avatar,c=a.timestamp,p=(X=d==null?void 0:d.show)!=null?X:!1,m=(re=c==null?void 0:c.show)!=null?re:!1,f=(ce=d==null?void 0:d.position)!=null?ce:"left",g=(oe=c==null?void 0:c.position)!=null?oe:"below",x=qy(e.role,i),v=y("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=By(e),S=(te=(J=e.content)==null?void 0:J.trim())!=null?te:"",O=M.length>0&&S===oi,k=vi((Q=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Q.streamAnimation),I=(we=(We=(le=o==null?void 0:o.widgetConfig)==null?void 0:le.features)==null?void 0:We.streamAnimation)==null?void 0:we.plugins,A=e.role==="assistant"&&k.type!=="none"?ha(k.type,I):null,H=e.role==="assistant"&&((Ye=A==null?void 0:A.isAnimating)==null?void 0:Ye.call(A,e))===!0,D=e.role==="assistant"&&A!==null&&(!!e.streaming||H);D&&(A!=null&&A.bubbleClass)&&v.classList.add(A.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),D&&A&&(A.containerClass&&N.classList.add(A.containerClass),N.style.setProperty("--persona-stream-step",`${k.speed}ms`),N.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let L=D?wi((Ge=e.content)!=null?Ge:"",k.buffer,A,e,!!e.streaming):(Oe=e.content)!=null?Oe:"",U=t({text:L,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=U;D&&(A==null?void 0:A.wrap)==="char"?V=ya(U,"char",e.id,{skipTags:A.skipTags}):D&&(A==null?void 0:A.wrap)==="word"&&(V=ya(U,"word",e.id,{skipTags:A.skipTags}));let ne=null;if(O?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",N.appendChild(ne)):N.innerHTML=V,D&&(A!=null&&A.useCaret)&&!O&&S){let Y=Ci(),pe=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=pe[pe.length-1];if(Ce!=null&&Ce.parentNode)Ce.parentNode.insertBefore(Y,Ce.nextSibling);else{let Ve=N.lastElementChild;Ve?Ve.appendChild(Y):N.appendChild(Y)}}if(m&&g==="inline"&&e.createdAt){let Y=Sg(e,c,"span");Y.classList.add("persona-timestamp-inline");let pe=N.lastElementChild;pe?pe.appendChild(Y):N.appendChild(Y)}if(M.length>0){let Y=Fy(M,!O&&!!S,()=>{O&&ne&&(ne.style.display="")});Y?v.appendChild(Y):O&&ne&&(ne.style.display="")}let Ie=Dy(e);if(Ie.length>0){let Y=_y(Ie);Y&&v.appendChild(Y)}let Ue=Ny(e);if(Ue.length>0){let Y=$y(Ue);Y&&v.appendChild(Y)}let Ae=Oy(e);if(Ae.length>0){let Y=jy(Ae);Y&&v.appendChild(Y)}if(v.appendChild(N),m&&g==="below"&&e.createdAt){let Y=Sg(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}let Le=e.role==="assistant"?Ry(e.stopReason,(tt=(de=o==null?void 0:o.widgetConfig)==null?void 0:de.copy)==null?void 0:tt.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(L&&L.trim()),pe=k.placeholder==="skeleton",Ce=pe&&k.buffer==="line"&&Y;if(Y)Ce&&v.appendChild(ba());else if(pe)v.appendChild(ba());else{let Ve=Kl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Ve&&v.appendChild(Ve)}}if(Le&&e.stopReason&&!e.streaming&&(S||(N.style.display="none"),v.appendChild(Wy(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=Gl(e,r,s);v.appendChild(Y)}if(!p||e.role==="system")return v;let ye=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),De=Uy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ye.append(v,De):ye.append(De,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ye},Tg=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ws(e,t,n,r,s,o)};var Hs=new Set,zy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vy=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
-
`):""},
|
|
27
|
+
`,n.addEventListener("click",t);let r=o=>{var O,k,I,A,H,D,N,L,U,V,ne,Ie,Ue;let a=(O=o.launcher)!=null?O:{},i=on(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Ae=(k=a.title)!=null?k:"Chat Assistant";d.textContent=Ae,d.setAttribute("title",Ae)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let Ae=(I=a.subtitle)!=null?I:"Here to help you get answers fast";c.textContent=Ae,c.setAttribute("title",Ae)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let Ae=(A=a.agentIconSize)!=null?A:"40px";if(m.style.height=Ae,m.style.width=Ae,m.innerHTML="",a.agentIconName){let Le=parseFloat(Ae)||24,_e=xe(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);_e?(m.appendChild(_e),m.style.display=""):(m.textContent=(H=a.agentIconText)!=null?H:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",m.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let Ae=(N=a.agentIconSize)!=null?N:"40px";f.style.height=Ae,f.style.width=Ae,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Ae=(L=a.callToActionIconSize)!=null?L:"32px";g.style.height=Ae,g.style.width=Ae,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let _e=parseFloat(Ae)||24,ye=Math.max(_e-Le,8),De=xe(a.callToActionIconName,ye,"currentColor",2);De?g.appendChild(De):g.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else g.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let x=a.position&&br[a.position]?br[a.position]:br["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${v} ${x}`,i||(n.style.zIndex=String((ne=a.zIndex)!=null?ne:Cn));let S="1px solid var(--persona-border, #e5e7eb)",R="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=(Ie=a.border)!=null?Ie:S,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,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="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var Eg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:s}=Ag(e),o=Tg(e,t),a={wrapper:n,panel:r,pillRoot:s},i={container:o.container,body:o.body,messagesWrapper:o.messagesWrapper,composerOverlay:o.composerOverlay,introTitle:o.introTitle,introSubtitle:o.introSubtitle},d={element:o.header,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper},c={footer:o.footer,form:o.composerForm,textarea:o.textarea,sendButton:o.sendButton,sendButtonWrapper:o.sendButtonWrapper,micButton:o.micButton,micButtonWrapper:o.micButtonWrapper,statusText:o.statusText,suggestions:o.suggestions,attachmentButton:o.attachmentButton,attachmentButtonWrapper:o.attachmentButtonWrapper,attachmentInput:o.attachmentInput,attachmentPreviewsContainer:o.attachmentPreviewsContainer,actionsRow:o.actionsRow,leftActions:o.leftActions,rightActions:o.rightActions,setSendButtonMode:o.setSendButtonMode,peekBanner:o.peekBanner,peekTextNode:o.peekTextNode};return{shell:a,panelElements:o,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},ql=({config:e,plugins:t,onToggle:n})=>{let r=t.find(o=>o.renderLauncher);if(r!=null&&r.renderLauncher){let o=r.renderLauncher({config:e,defaultRenderer:()=>Ul(e,n).element,onToggle:n});if(o)return{instance:null,element:o}}let s=Ul(e,n);return{instance:s,element:s.element}};var Oy=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}},Fy=(e,t)=>{if(!e)return null;let n=Oy(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},_y=(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},$y=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},zl=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(":"))},Vl=320,kg=320,jy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Uy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),qy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),zy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Vy=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Vl}px`,c.style.maxHeight=`${kg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),$y(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Ky=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(!zl(r.audio))return;let s=y("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Vl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Gy=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(!zl(r.video))return;let s=y("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Vl}px`,s.style.maxHeight=`${kg}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Jy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!zl(r.data))return;let s=y("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},es=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},Kl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:es};if(t){let s=t(r);if(s!==null)return s}return es()},Qy=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=y("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Mg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?r.textContent=t.format(s):r.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Xy=(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},Gl=(e,t,n)=>{var x,v,M,S,R,O,k;let r=(x=t.showCopy)!=null?x:!0,s=(v=t.showUpvote)!=null?v:!0,o=(M=t.showDownvote)!=null?M:!0,a=(S=t.showReadAloud)!=null?S:!1;if(!r&&!s&&!o&&!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=(R=t.visibility)!=null?R:"hover",d=(O=t.align)!=null?O:"right",c=(k=t.layout)!=null?k:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(I,A,H)=>{let D=qt({icon:I,label:A,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",H),D};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),s&&f.appendChild(g("thumbs-up","Upvote","upvote")),o&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Ws=(e,t,n,r,s,o)=>{var ie,X,re,ce,oe,J,te,ze,Q,le,We,we,Ye,Ge,Oe,de,tt;let a=n!=null?n:{},i=(ie=a.layout)!=null?ie:"bubble",d=a.avatar,c=a.timestamp,p=(X=d==null?void 0:d.show)!=null?X:!1,m=(re=c==null?void 0:c.show)!=null?re:!1,f=(ce=d==null?void 0:d.position)!=null?ce:"left",g=(oe=c==null?void 0:c.position)!=null?oe:"below",x=Xy(e.role,i),v=y("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=jy(e),S=(te=(J=e.content)==null?void 0:J.trim())!=null?te:"",O=M.length>0&&S===oi,k=vi((Q=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Q.streamAnimation),I=(we=(We=(le=o==null?void 0:o.widgetConfig)==null?void 0:le.features)==null?void 0:We.streamAnimation)==null?void 0:we.plugins,A=e.role==="assistant"&&k.type!=="none"?ha(k.type,I):null,H=e.role==="assistant"&&((Ye=A==null?void 0:A.isAnimating)==null?void 0:Ye.call(A,e))===!0,D=e.role==="assistant"&&A!==null&&(!!e.streaming||H);D&&(A!=null&&A.bubbleClass)&&v.classList.add(A.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),e.streaming&&N.classList.add("persona-content-streaming"),D&&A&&(A.containerClass&&N.classList.add(A.containerClass),N.style.setProperty("--persona-stream-step",`${k.speed}ms`),N.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let L=D?wi((Ge=e.content)!=null?Ge:"",k.buffer,A,e,!!e.streaming):(Oe=e.content)!=null?Oe:"",U=t({text:L,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=U;D&&(A==null?void 0:A.wrap)==="char"?V=ya(U,"char",e.id,{skipTags:A.skipTags}):D&&(A==null?void 0:A.wrap)==="word"&&(V=ya(U,"word",e.id,{skipTags:A.skipTags}));let ne=null;if(O?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",N.appendChild(ne)):N.innerHTML=V,D&&(A!=null&&A.useCaret)&&!O&&S){let Y=Ci(),pe=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=pe[pe.length-1];if(Ce!=null&&Ce.parentNode)Ce.parentNode.insertBefore(Y,Ce.nextSibling);else{let Ve=N.lastElementChild;Ve?Ve.appendChild(Y):N.appendChild(Y)}}if(m&&g==="inline"&&e.createdAt){let Y=Mg(e,c,"span");Y.classList.add("persona-timestamp-inline");let pe=N.lastElementChild;pe?pe.appendChild(Y):N.appendChild(Y)}if(M.length>0){let Y=Vy(M,!O&&!!S,()=>{O&&ne&&(ne.style.display="")});Y?v.appendChild(Y):O&&ne&&(ne.style.display="")}let Ie=Uy(e);if(Ie.length>0){let Y=Ky(Ie);Y&&v.appendChild(Y)}let Ue=qy(e);if(Ue.length>0){let Y=Gy(Ue);Y&&v.appendChild(Y)}let Ae=zy(e);if(Ae.length>0){let Y=Jy(Ae);Y&&v.appendChild(Y)}if(v.appendChild(N),m&&g==="below"&&e.createdAt){let Y=Mg(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}let Le=e.role==="assistant"?Fy(e.stopReason,(tt=(de=o==null?void 0:o.widgetConfig)==null?void 0:de.copy)==null?void 0:tt.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(L&&L.trim()),pe=k.placeholder==="skeleton",Ce=pe&&k.buffer==="line"&&Y;if(Y)Ce&&v.appendChild(ba());else if(pe)v.appendChild(ba());else{let Ve=Kl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Ve&&v.appendChild(Ve)}}if(Le&&e.stopReason&&!e.streaming&&(S||(N.style.display="none"),v.appendChild(_y(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=Gl(e,r,s);v.appendChild(Y)}if(!p||e.role==="system")return v;let ye=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),De=Qy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ye.append(v,De):ye.append(De,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ye},Lg=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ws(e,t,n,r,s,o)};var Hs=new Set,Yy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Zy=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
28
|
+
`):""},Pg=(e,t)=>{let n=Hs.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=xe(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},Jl=(e,t)=>{var Ue,Ae,Le,_e,ye,De,ie,X,re,ce,oe;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Ae=(Ue=t==null?void 0:t.features)==null?void 0:Ue.reasoningDisplay)!=null?Ae:{},o=s.expandable!==!1,a=o&&Hs.has(e.id),i=n.status!=="complete",d=Zy(e,(Le=s.previewMaxLines)!=null?Le:3),c=y("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(_e=t==null?void 0:t.reasoning)!=null?_e:{},x=String((ye=n.startedAt)!=null?ye:Date.now()),v=()=>{let J=y("span","");return J.setAttribute("data-tool-elapsed",x),J.textContent=Xa(n),J},M=(De=g.renderCollapsedSummary)==null?void 0:De.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Xa(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,p.appendChild(m)):M instanceof HTMLElement?p.appendChild(M):(m.textContent=f,p.appendChild(m));let S=y("span","persona-text-xs persona-text-persona-primary");S.textContent=Mm(n),p.appendChild(S);let R=(ie=s.loadingAnimation)!=null?ie:"none",O=g.activeTextTemplate,k=g.completeTextTemplate,I=i?O:k,A=M instanceof HTMLElement,H=(J,te,ze)=>{let Q=ze;for(let le of te){let We=y("span","persona-tool-char");We.style.setProperty("--char-index",String(Q)),We.textContent=le===" "?"\xA0":le,J.appendChild(We),Q++}return Q},D=(J,te)=>{m.textContent="";let ze=Ya(J,""),Q=0;for(let le of ze){let We=le.styles.length>0?(()=>{let we=y("span",le.styles.map(Ye=>`persona-tool-text-${Ye}`).join(" "));return m.appendChild(we),we})():m;if(le.isDuration&&i)We.appendChild(v());else{let we=le.isDuration?Xa(n):le.text;te?Q=H(We,we,Q):We.appendChild(document.createTextNode(we))}}};if(!A&&I)if(S.style.display="none",m.style.display="",i&&R!=="none"){let J=(X=g.loadingAnimationDuration)!=null?X:2e3;m.setAttribute("data-preserve-animation","true"),R==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),D(I,!1)):(m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),R==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),D(I,!0))}else D(I,!1);else if(!A&&i&&R!=="none"){m.style.display="";let J=(re=g.loadingAnimationDuration)!=null?re:2e3;if(m.setAttribute("data-preserve-animation","true"),R==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`);else{m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),R==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let te=m.textContent||f;m.textContent="",H(m,te,0)}n.status==="complete"&&(m.style.display="none")}else A||(n.status==="complete"?m.style.display="none":m.style.display="");let N=null;if(o){N=y("div","persona-flex persona-items-center");let te=xe(a?"chevron-up":"chevron-down",16,"currentColor",2);te?N.appendChild(te):N.textContent=a?"Hide":"Show";let ze=y("div","persona-flex persona-items-center persona-ml-auto");ze.append(N),c.append(p,ze)}else c.append(p);let L=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(L.setAttribute("data-persona-collapsed-preview","reasoning"),L.style.display="none",L.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let J=(oe=(ce=t==null?void 0:t.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:oe.call(ce,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Yy(L,J)||(L.textContent=d),L.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(c,L),r;let U=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let V=n.chunks.join(""),ne=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(ne),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let te=xe(a?"chevron-up":"chevron-down",16,"currentColor",2);te?N.appendChild(te):N.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",L.style.display=a?"none":L.textContent||L.childNodes.length?"":"none"})(),r.append(c,L,U),r};var Bs=new Set,eb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),tb=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
27
29
|
`);let s=Ss(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
28
|
-
`):""},Ql=(e,t)=>{var n,r,s;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=(s=t.codeBlockTextColor)!=null?s:"var(--persona-text, #171717)"},Jy=(e,t)=>{var p,m,f,g,x;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=Gy(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Am(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&d.activeTextTemplate?c=Tl(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Tl(n,d.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Mg=(e,t,n)=>{var p;let r=Bs.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",f=xe(r?"chevron-up":"chevron-down",16,m,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Xl=(e,t)=>{var V,ne,Ie,Ue,Ae,Le,_e,ye,De;let n=e.toolCall,r=(V=t==null?void 0:t.toolCall)!=null?V:{},s=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let o=(Ie=(ne=t==null?void 0:t.features)==null?void 0:ne.toolCallDisplay)!=null?Ie:{},a=o.expandable!==!1,i=a&&Bs.has(e.id),{summary:d,previewText:c,isActive:p}=Jy(e,t),m=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let x=String((Ue=n.startedAt)!=null?Ue:Date.now()),v=()=>{let ie=y("span","");return ie.setAttribute("data-tool-elapsed",x),ie.textContent=aa(n),ie},M=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(Ae=o.collapsedMode)!=null?Ae:"tool-call",isActive:p,config:t!=null?t:{},elapsed:aa(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(g.textContent=M,f.appendChild(g)):M instanceof HTMLElement?f.appendChild(M):(g.textContent=d,f.appendChild(g));let S=(_e=o.loadingAnimation)!=null?_e:"none",R=r.activeTextTemplate,O=r.completeTextTemplate,k=p?R:O,I=M instanceof HTMLElement,A=(ie,X,re)=>{let ce=re;for(let oe of X){let J=y("span","persona-tool-char");J.style.setProperty("--char-index",String(ce)),J.textContent=oe===" "?"\xA0":oe,ie.appendChild(J),ce++}return ce},H=(ie,X)=>{var J;g.textContent="";let re=((J=n.name)==null?void 0:J.trim())||"tool",ce=Ya(ie,re),oe=0;for(let te of ce){let ze=te.styles.length>0?(()=>{let Q=y("span",te.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(Q),Q})():g;if(te.isDuration&&p)ze.appendChild(v());else{let Q=te.isDuration?aa(n):te.text;X?oe=A(ze,Q,oe):ze.appendChild(document.createTextNode(Q))}}};if(!I)if(p&&S!=="none"){let ie=(ye=r.loadingAnimationDuration)!=null?ye:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),k&&H(k,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)H(k,!0);else{let X=g.textContent||d;g.textContent="",A(g,X,0)}}else k&&H(k,!1);let D=null;if(a){D=y("div","persona-flex persona-items-center");let ie=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=xe(i?"chevron-up":"chevron-down",16,ie,2);X?D.appendChild(X):D.textContent=i?"Hide":"Show";let re=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(D),m.append(f,re)}else m.append(f);let N=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let ie=(De=r.renderCollapsedPreview)==null?void 0:De.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Ky(N,ie)||(N.textContent=c),N.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,N),s;let L=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",r.contentBackgroundColor&&(L.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(L.style.color=r.contentTextColor),r.contentPaddingX&&(L.style.paddingLeft=r.contentPaddingX,L.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(L.style.paddingTop=r.contentPaddingY,L.style.paddingBottom=r.contentPaddingY),n.name){let ie=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ie.style.color=r.contentTextColor:r.headerTextColor&&(ie.style.color=r.headerTextColor),ie.textContent=n.name,L.appendChild(ie)}if(n.args!==void 0){let ie=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",Ql(re,r),re.textContent=Ss(n.args),ie.append(X,re),L.appendChild(ie)}if(n.chunks&&n.chunks.length){let ie=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",Ql(re,r),re.textContent=n.chunks.join(""),ie.append(X,re),L.appendChild(ie)}if(n.status==="complete"&&n.result!==void 0){let ie=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",Ql(re,r),re.textContent=Ss(n.result),ie.append(X,re),L.appendChild(ie)}if(n.status==="complete"&&typeof n.duration=="number"){let ie=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ie.style.color=r.contentTextColor),ie.textContent=`Duration: ${n.duration}ms`,L.appendChild(ie)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let ie=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=xe(i?"chevron-up":"chevron-down",16,ie,2);X?D.appendChild(X):D.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),s.append(m,N,L),s};var Wi=new Map,Qy=e=>{let n=(e.startsWith(Vr)?e.slice(Vr.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)},kg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Lg=(e,t)=>{var r,s,o;let n=(s=(r=kg(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=Wi.get(e))!=null?o:n==="expanded"},Pg=(e,t,n)=>{var a,i;let r=kg(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=xe(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},Ig=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=Lg(e,n);Pg(r,o,n),s.style.display=o?"":"none"};var Hi=(e,t)=>{var H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De,ie;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(H=r==null?void 0:r.backgroundColor)!=null?H:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(D=r==null?void 0:r.borderColor)!=null?D:"var(--persona-approval-border, #fef08a)",o.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(N=r==null?void 0:r.titleColor)!=null?N:"currentColor",p=xe(d,20,c,2);p&&i.appendChild(p);let m=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!s){let X=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),f.appendChild(X)}m.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Vr)?gl(n.toolName):void 0,M=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),S=!n.toolName,R=M||(S?n.description:`The assistant wants to use \u201C${v!=null?v:Qy(n.toolName)}\u201D.`),O=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(O.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(O.style.color=r.descriptionColor),O.textContent=R,m.appendChild(O),n.reason){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let re=y("span","persona-font-medium");re.textContent=`${(V=r==null?void 0:r.reasonLabel)!=null?V:"Agent's stated reason:"} `,X.appendChild(re),X.appendChild(document.createTextNode(n.reason)),m.appendChild(X)}let k=(ne=r==null?void 0:r.detailsDisplay)!=null?ne:"collapsed",I=!!n.description&&!S,A=I||!!n.parameters;if(k!=="hidden"&&A){let X=Lg(e.id,t),re=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");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let ce=y("span");ce.setAttribute("data-approval-details-label","true");let oe=y("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),re.append(ce,oe),Pg(re,X,t),m.appendChild(re);let J=y("div");if(J.setAttribute("data-approval-details","true"),J.style.display=X?"":"none",I){let te=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=n.description,J.appendChild(te)}if(n.parameters){let te=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&&(te.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=Ss(n.parameters),J.appendChild(te)}m.appendChild(J)}if(s){let X=y("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let re=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");re.type="button",re.style.backgroundColor=(Ie=r==null?void 0:r.approveButtonColor)!=null?Ie:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(Ue=r==null?void 0:r.approveButtonTextColor)!=null?Ue:"#ffffff",re.setAttribute("data-approval-action","approve");let ce=xe("shield-check",14,(Ae=r==null?void 0:r.approveButtonTextColor)!=null?Ae:"#ffffff",2);ce&&(ce.style.marginRight="4px",re.appendChild(ce));let oe=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");re.appendChild(oe);let J=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");J.type="button",J.style.backgroundColor=(_e=r==null?void 0:r.denyButtonColor)!=null?_e:"transparent",J.style.color=(ye=r==null?void 0:r.denyButtonTextColor)!=null?ye:"var(--persona-feedback-error, #dc2626)",J.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,J.setAttribute("data-approval-action","deny");let te=xe("shield-x",14,(De=r==null?void 0:r.denyButtonTextColor)!=null?De:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",J.appendChild(te));let ze=document.createTextNode((ie=r==null?void 0:r.denyLabel)!=null?ie:"Deny");J.appendChild(ze),X.append(re,J),m.appendChild(X)}return a.append(i,m),o.appendChild(a),o};var Rg=e=>{let t=[],n=null;return{buttons:t,render:(s,o,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!s||!s.length||!p&&(i!=null?i:o?o.getMessages():[]).some(M=>M.role==="user"))return;let m=document.createDocumentFragment(),f=o?o.isStreaming():!1,g=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(s.forEach(x=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=x,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),o.sendMessage(x))}),m.appendChild(v),t.push(v)}),e.appendChild(m),p){let x=JSON.stringify(s);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var Sa=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 Aa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Xy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Yy=new Set(["step_start","execution_start"]),Zy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),eb=new Set(["step_complete","agent_turn_complete"]),tb=new Set(["flow_complete","agent_complete"]),Wg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Bg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ts=(e,t)=>{let n=e[t];return Bg(n)?n:void 0};function Yl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Bi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function nb(e,t){return typeof t.type=="string"?t.type:e}function rb(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function ob(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Hg(e){var r,s,o,a,i;let t=ts(e,"result"),n=[ts(e,"tokens"),ts(e,"totalTokens"),t?ts(t,"tokens"):void 0,ts(e,"usage"),t?ts(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(s=(r=Yn(d.output))!=null?r:Yn(d.outputTokens))!=null?s:Yn(d.completionTokens);if(c!==void 0)return c}return(i=(o=Yn(e.outputTokens))!=null?o:Yn(e.completionTokens))!=null?i:t?(a=Yn(t.outputTokens))!=null?a:Yn(t.completionTokens):void 0}function sb(e){var n,r,s,o,a;let t=ts(e,"result");return(a=(s=(r=(n=Yn(e.executionTime))!=null?n:Yn(e.executionTimeMs))!=null?r:Yn(e.execution_time))!=null?s:Yn(e.duration))!=null?a:t?(o=Yn(t.executionTime))!=null?o:Yn(t.executionTimeMs):void 0}function ab(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=ab){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Bi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!Bg(n)){Wg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=nb(t,n),s=this.now();if(Xy.has(r)){this.startRun(s);return}if(Yy.has(r)){this.run||this.startRun(s);return}if(Zy.has(r)){if(!ob(r,n))return;let a=rb(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Yl(i.visibleCharCount),c=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Bi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(eb.has(r)){if(!this.run)return;let a=this.run,i=Hg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Yl(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:Bi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(tb.has(r)){if(!this.run)return;let a=this.run,i=Hg(n),d=i!=null?i:a.exactOutputTokens+Yl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:Bi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(Wg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=sb(n);return o!=null?o:r-t.startedAt}};function Ds(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var ib={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},lb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},cb=["flowName","stepName","reasoningText","text","name","tool","toolName"],db=100;function pb(e,t){let n={...ib,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return lb}function ub(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function mb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function gb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function fb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function hb(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function yb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function bb(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function xb(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Zl(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ds(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(m()),c;function m(){var V,ne;let g=y("div",""),x=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=xe(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.appendChild(M);let S=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=(V=r.timestampFormat)!=null?V:"relative";S.textContent=R==="relative"?ub(e.timestamp,n):mb(e.timestamp);let O=null;r.showSequenceNumbers!==!1&&(O=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),O.textContent=String(t+1));let k=pb(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 A=(ne=r.descriptionFields)!=null?ne:cb,H=gb(e.payload,A),D=null;H&&(D=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),D.textContent=H);let N=y("div","persona-flex-1 persona-min-w-0"),L=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),U=xe("clipboard","12px","currentColor",1.5);return U&&L.appendChild(U),L.addEventListener("click",async Ie=>{Ie.stopPropagation(),await fb(hb(e)),L.innerHTML="";let Ue=xe("check","12px","currentColor",1.5);Ue&&L.appendChild(Ue),setTimeout(()=>{L.innerHTML="";let Ae=xe("clipboard","12px","currentColor",1.5);Ae&&L.appendChild(Ae)},1500)}),x.appendChild(v),x.appendChild(S),O&&x.appendChild(O),x.appendChild(I),D&&x.appendChild(D),x.appendChild(N),x.appendChild(L),g.appendChild(x),d&&g.appendChild(xb(e,a,i)),g}}function Dg(e){var x,v,M,S,R;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",m=(R=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?R:{},f=o.find(O=>O.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let O=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(O)return{element:O,update:()=>{},destroy:()=>{}}}return g();function g(){let O=m.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ds(k,O==null?void 0:O.panel);let I=[],A="",H="",D=null,N=[],L={},U=0,V=yi(),ne=0,Ie=0,Ue=!1,Ae=null,Le=!1,_e=0,ye=new Set,De=new Map,ie="",X="",re=null,ce,oe,J,te,ze,Q=null,le=null,We=null;function we(){let K=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ue=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");Ds(ue,O==null?void 0:O.headerBar);let Me=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Me.textContent="Events",ce=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"),ce.textContent="0",a){le=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let Zn=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Zn.textContent="Throughput",Q=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"),Q.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 Sn=le,tn=We,In=()=>{if(!tn.textContent)return;let vt=Sn.getBoundingClientRect(),Nn=K.getBoundingClientRect();tn.style.left=`${vt.left-Nn.left}px`,tn.style.top=`${vt.bottom-Nn.top+4}px`,tn.style.display="block"},vr=()=>{tn.style.display="none"};le.addEventListener("mouseenter",In),le.addEventListener("mouseleave",vr),le.appendChild(Zn),le.appendChild(Q)}let xt=y("div","persona-flex-1");oe=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 Zt=y("option","");Zt.value="",Zt.textContent="All events",oe.appendChild(Zt),J=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"),J.type="button",J.title="Copy All";let mn=xe("clipboard-copy","12px","currentColor",1.5);mn&&J.appendChild(mn);let Ht=y("span","persona-text-xs");Ht.textContent="Copy All",J.appendChild(Ht),ue.appendChild(Me),ue.appendChild(ce),le&&ue.appendChild(le),ue.appendChild(xt),ue.appendChild(oe),ue.appendChild(J);let rt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ds(rt,O==null?void 0:O.searchBar);let Wt=xe("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");Wt&&ct.appendChild(Wt),te=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"),Ds(te,O==null?void 0:O.searchInput),te.type="text",te.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let Gt=xe("x","12px","currentColor",2);return Gt&&ze.appendChild(Gt),rt.appendChild(ct),rt.appendChild(te),rt.appendChild(ze),K.appendChild(ue),K.appendChild(rt),We&&K.appendChild(We),K}let Ye,Ge=o.find(K=>K.renderEventStreamToolbar);if(Ge!=null&&Ge.renderEventStreamToolbar&&s){let K=Ge.renderEventStreamToolbar({config:s,defaultRenderer:()=>we(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ue=>{A=ue,It(),yn()},onSearchChange:ue=>{H=ue,It(),yn()}});Ye=K!=null?K:we()}else Ye=we();let Oe=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";function de(){if(!a||!Q||!le)return;let K=a();Q.textContent=yb(K);let ue=bb(K);We&&(We.textContent=ue,ue||(We.style.display="none")),ue?le.setAttribute("aria-label",ue):le.removeAttribute("aria-label")}let tt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let pe=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");Ds(pe,O==null?void 0:O.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Ce=xe(c,"14px","currentColor",2);Ce&&pe.appendChild(Ce);let Ve=y("span","");Ve.textContent=p,pe.appendChild(Ve);let Pt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Pt.style.display="none",tt.appendChild(Y),tt.appendChild(Pt),tt.appendChild(pe),k.setAttribute("tabindex","0"),k.appendChild(Ye),k.appendChild(Oe),k.appendChild(tt);function Te(){let K=t.getAll(),ue={};for(let Ht of K)ue[Ht.type]=(ue[Ht.type]||0)+1;let Me=Object.keys(ue).sort(),xt=Me.length!==N.length||!Me.every((Ht,rt)=>Ht===N[rt]),Zt=!xt&&Me.some(Ht=>ue[Ht]!==L[Ht]),en=K.length!==Object.values(L).reduce((Ht,rt)=>Ht+rt,0);if(!xt&&!Zt&&!en||(N=Me,L=ue,!oe))return;let mn=oe.value;if(oe.options[0].textContent="All events",xt){for(;oe.options.length>1;)oe.remove(1);for(let Ht of Me){let rt=y("option","");rt.value=Ht,rt.textContent=`${Ht} (${ue[Ht]||0})`,oe.appendChild(rt)}mn&&Me.includes(mn)?oe.value=mn:mn&&(oe.value="",A="")}else for(let Ht=1;Ht<oe.options.length;Ht++){let rt=oe.options[Ht];rt.textContent=`${rt.value} (${ue[rt.value]||0})`}}function ge(){let K=t.getAll();if(A&&(K=K.filter(ue=>ue.type===A)),H){let ue=H.toLowerCase();K=K.filter(Me=>Me.type.toLowerCase().includes(ue)||Me.payload.toLowerCase().includes(ue))}return K}function hn(){return A!==""||H!==""}function It(){U=0,ne=0,V.resume(),pe.style.display="none"}function sn(K){ye.has(K)?ye.delete(K):ye.add(K),re=K;let ue=Y.scrollTop,Me=V.isFollowing();Le=!0,V.pause(),yn(),Y.scrollTop=ue,Me&&V.resume(),Le=!1}function xr(){return Yo(Y,50)}function yn(){Ie=Date.now(),Ue=!1,de(),Te();let K=t.getEvictedCount();K>0?(Oe.textContent=`${K.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",I=ge();let ue=I.length,Me=t.getSize()>0;ce&&(ce.textContent=String(t.getSize())),ue===0&&Me&&hn()?(Pt.textContent=H?`No events matching '${H}'`:"No events matching filter",Pt.style.display="",Y.style.display="none"):(Pt.style.display="none",Y.style.display=""),J&&(J.title=hn()?`Copy Filtered (${ue})`:"Copy All"),d&&!V.isFollowing()&&ue>U&&(ne+=ue-U,Ve.textContent=p?`${p}${ne>0?` (${ne})`:""}`:"",pe.style.display=""),U=ue;let xt=t.getAll(),Zt=xt.length>0?xt[0].timestamp:0,en=new Set(I.map(rt=>rt.id));for(let rt of ye)en.has(rt)||ye.delete(rt);let mn=A!==ie||H!==X,Ht=De.size===0&&I.length>0;if(mn||Ht||I.length===0){Y.innerHTML="",De.clear();let rt=document.createDocumentFragment();for(let Wt=0;Wt<I.length;Wt++){let ct=Zl(I[Wt],Wt,Zt,m,ye,sn,o,s);De.set(I[Wt].id,ct),rt.appendChild(ct)}Y.appendChild(rt),ie=A,X=H,re=null}else{if(re!==null){let Wt=De.get(re);if(Wt&&Wt.parentNode===Y){let ct=I.findIndex(Gt=>Gt.id===re);if(ct>=0){let Gt=Zl(I[ct],ct,Zt,m,ye,sn,o,s);Y.insertBefore(Gt,Wt),Wt.remove(),De.set(re,Gt)}}re=null}let rt=new Set(I.map(Wt=>Wt.id));for(let[Wt,ct]of De)rt.has(Wt)||(ct.remove(),De.delete(Wt));for(let Wt=0;Wt<I.length;Wt++){let ct=I[Wt];if(!De.has(ct.id)){let Gt=Zl(ct,Wt,Zt,m,ye,sn,o,s);De.set(ct.id,Gt),Y.appendChild(Gt)}}}V.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function Ke(){if(Date.now()-Ie>=db){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),yn();return}Ue||(Ue=!0,Ae=requestAnimationFrame(()=>{Ae=null,yn()}))}let E=(K,ue)=>{if(!J)return;J.innerHTML="";let Me=xe(K,"12px","currentColor",1.5);Me&&J.appendChild(Me);let xt=y("span","persona-text-xs");xt.textContent="Copy All",J.appendChild(xt),setTimeout(()=>{J.innerHTML="";let Zt=xe("clipboard-copy","12px","currentColor",1.5);Zt&&J.appendChild(Zt);let en=y("span","persona-text-xs");en.textContent="Copy All",J.appendChild(en),J.disabled=!1},ue)},me=async()=>{if(J){J.disabled=!0;try{let K;hn()?K=I:n?(K=await n(),K.length===0&&(K=t.getAll())):K=t.getAll();let ue=K.map(Me=>{try{return JSON.parse(Me.payload)}catch{return Me.payload}});await navigator.clipboard.writeText(JSON.stringify(ue,null,2)),E("check",1500)}catch{E("x",1500)}}},ke=()=>{oe&&(A=oe.value,It(),yn())},Ee=()=>{!te||!ze||(ze.style.display=te.value?"":"none",D&&clearTimeout(D),D=setTimeout(()=>{H=te.value,It(),yn()},150))},Re=()=>{!te||!ze||(te.value="",H="",ze.style.display="none",D&&clearTimeout(D),It(),yn())},nt=()=>{if(Le)return;let K=Y.scrollTop,{action:ue,nextLastScrollTop:Me}=bi({following:V.isFollowing(),currentScrollTop:K,lastScrollTop:_e,nearBottom:xr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_e=Me,ue==="resume"?(V.resume(),ne=0,pe.style.display="none"):ue==="pause"&&(V.pause(),d&&(Ve.textContent=p,pe.style.display=""))},Qe=K=>{let ue=xi({following:V.isFollowing(),deltaY:K.deltaY,nearBottom:xr(),resumeWhenNearBottom:!0});ue==="pause"?(V.pause(),d&&(Ve.textContent=p,pe.style.display="")):ue==="resume"&&(V.resume(),ne=0,pe.style.display="none")},ut=()=>{d&&(Y.scrollTop=Y.scrollHeight,V.resume(),ne=0,pe.style.display="none")},Rt=K=>{let ue=K.target;if(!ue||ue.closest("button"))return;let Me=ue.closest("[data-event-id]");if(!Me)return;let xt=Me.getAttribute("data-event-id");xt&&sn(xt)},q=K=>{if((K.metaKey||K.ctrlKey)&&K.key==="f"){K.preventDefault(),te==null||te.focus(),te==null||te.select();return}K.key==="Escape"&&(te&&document.activeElement===te?(Re(),te.blur(),k.focus()):r&&r())};J&&J.addEventListener("click",me),oe&&oe.addEventListener("change",ke),te&&te.addEventListener("input",Ee),ze&&ze.addEventListener("click",Re),Y.addEventListener("scroll",nt),Y.addEventListener("wheel",Qe,{passive:!0}),Y.addEventListener("click",Rt),pe.addEventListener("click",ut),k.addEventListener("keydown",q);function at(){D&&clearTimeout(D),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),Ue=!1,De.clear(),J&&J.removeEventListener("click",me),oe&&oe.removeEventListener("change",ke),te&&te.removeEventListener("input",Ee),ze&&ze.removeEventListener("click",Re),Y.removeEventListener("scroll",nt),Y.removeEventListener("wheel",Qe),Y.removeEventListener("click",Rt),pe.removeEventListener("click",ut),k.removeEventListener("keydown",q)}return{element:k,update:Ke,destroy:at}}}function Ng(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(g)}else m.textContent=a;if(c.append(p,m),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Og=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Ng(e,t)});if(p)return p}return Ng(e,t)};var ec=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)})}},Zr=new ec;Zr.register("PersonaArtifactCard",Og);function vb(e){var s;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Fg(e,t){var oe,J,te,ze;let n=(J=(oe=e.features)==null?void 0:oe.artifacts)==null?void 0:J.layout,s=((te=n==null?void 0:n.toolbarPreset)!=null?te:"default")==="document",o=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?zo(e.markdown):null,i=bs(e.sanitize),d=Q=>{let le=a?a(Q):Rr(Q);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};c&&c.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let m=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let f=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let v="rendered",M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),R=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),O=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,A=n==null?void 0:n.documentToolbarCopyMenuItems,H=!!(I&&A&&A.length>0),D=null,N,L=null,U=null;if(s&&(k||I)&&!H){if(N=k?wa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let Q=xe("chevron-down",14,"currentColor",2);Q&&N.appendChild(Q)}}else s&&H?(D=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=k?wa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=qt({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"}}),D.append(N,L)):s?N=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=qt({icon:"copy",label:"Copy"});let V=s?qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):qt({icon:"refresh-cw",label:"Refresh"}),ne=s?qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):qt({icon:"x",label:"Close"}),Ie=()=>{var Ye,Ge,Oe;let Q=(Ye=De.find(de=>de.id===ie))!=null?Ye:De[De.length-1],le=(Ge=Q==null?void 0:Q.id)!=null?Ge:null,We=(Q==null?void 0:Q.artifactType)==="markdown"&&(Oe=Q.markdown)!=null?Oe:"",we=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:We,jsonPayload:we,id:le}},Ue=async()=>{var Ye;let{markdown:Q,jsonPayload:le}=Ie(),We=(Ye=De.find(Ge=>Ge.id===ie))!=null?Ye:De[De.length-1],we=(We==null?void 0:We.artifactType)==="markdown"?Q:We?le:"";try{await navigator.clipboard.writeText(we)}catch{}};if(N.addEventListener("click",async()=>{let Q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Q&&H){let{markdown:le,jsonPayload:We,id:we}=Ie();try{await Q({actionId:"primary",artifactId:we,markdown:le,jsonPayload:We})}catch{}return}await Ue()}),L&&(A!=null&&A.length)){let Q=()=>{var We;return(We=m.closest("[data-persona-root]"))!=null?We:document.body},le=()=>{U=Mo({items:A.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:we,jsonPayload:Ye,id:Ge}=Ie(),Oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:We,artifactId:Ge,markdown:we,jsonPayload:Ye}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(we):We==="json"||We==="source"?await navigator.clipboard.writeText(Ye):await navigator.clipboard.writeText(we||Ye)}catch{}},anchor:D!=null?D:L,position:"bottom-right",portal:Q()})};m.isConnected?le():requestAnimationFrame(le),L.addEventListener("click",We=>{We.stopPropagation(),U==null||U.toggle()})}V.addEventListener("click",async()=>{var Q;try{await((Q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Q.call(n))}catch{}re()}),ne.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let Ae=()=>{s&&(S.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};S.addEventListener("click",()=>{v="rendered",Ae(),re()}),R.addEventListener("click",()=>{v="source",Ae(),re()});let Le=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),M.append(S,R),D?O.append(D,V,ne):O.append(N,V,ne),f.append(M,Le,O),Ae()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let _e=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"),ye=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(_e.style.paddingLeft=o,_e.style.paddingRight=o,ye.style.padding=o),m.appendChild(f),m.appendChild(_e),m.appendChild(ye);let De=[],ie=null,X=!1,re=()=>{var we,Ye,Ge,Oe;let Q=s&&De.length<=1;_e.classList.toggle("persona-hidden",Q),_e.replaceChildren();for(let de of De){let tt=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");tt.type="button",tt.textContent=de.title||de.id.slice(0,8),de.id===ie&&tt.classList.add("persona-bg-persona-container","persona-border-persona-border"),tt.addEventListener("click",()=>t.onSelect(de.id)),_e.appendChild(tt)}ye.replaceChildren();let le=ie&&De.find(de=>de.id===ie)||De[De.length-1];if(!le)return;if(s){let de=le.artifactType==="markdown"?"MD":(we=le.component)!=null?we:"Component",Y=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Y} \xB7 ${de}`}else g.textContent="Artifacts";if(le.artifactType==="markdown"){if(s&&v==="source"){let tt=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");tt.textContent=(Ye=le.markdown)!=null?Ye:"",ye.appendChild(tt);return}let de=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");de.innerHTML=d((Ge=le.markdown)!=null?Ge:""),ye.appendChild(de);return}let We=le.component?Zr.get(le.component):void 0;if(We){let tt={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=We((Oe=le.props)!=null?Oe:{},tt);if(Y){ye.appendChild(Y);return}}catch{}}ye.appendChild(vb(le))},ce=()=>{var le;let Q=De.length>0;if(m.classList.toggle("persona-hidden",!Q),c){let We=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ye=((le=We==null?void 0:We.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&Ye&&X?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(Q){var le,We,we;De=Q.artifacts,ie=(we=(We=Q.selectedId)!=null?We:(le=Q.artifacts[Q.artifacts.length-1])==null?void 0:le.id)!=null?we:null,De.length>0&&(X=!0),re(),ce()},setMobileOpen(Q){X=Q,!Q&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ce()}}}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 _g(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!cr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function wb(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Di(e,t){var d,c,p,m,f,g,x,v,M,S;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"),wb(e),_g(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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=(S=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),_g(e,t)}var $g=["panel","seamless"];function Ni(e,t){var i,d,c,p,m,f;for(let g of $g)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!cr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",s=$g.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function jg(e,t){var n,r,s;return!t||!cr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Cb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Sb(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Ab(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Tb(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Ug(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function qg(e,t,n,r,s,o){let a=Cb(s,200),i=Tb(t,n,r,200);i=Math.max(a,i);let d=Sb(o);return d!==null&&(i=Math.min(i,d)),Ab(e,a,i)}var zg={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"}},tc=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,M;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=zg[a])!=null?v:zg.init;o.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let S=y("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var A,H;let R=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${S.name}`;let O=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");O.textContent=S.label,R.appendChild(O);let k=(A=S.type)!=null?A:"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}-${S.name}`,I.name=S.name,I.placeholder=(H=S.placeholder)!=null?H:"",S.required&&(I.required=!0),R.appendChild(I),p.appendChild(R)});let m=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(M=i.submitLabel)!=null?M:"Submit",m.appendChild(f),m.appendChild(g),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async S=>{var I,A;S.preventDefault();let R=(I=n.formEndpoint)!=null?I:"/form",O=new FormData(p),k={};O.forEach((H,D)=>{k[D]=H}),k.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let H=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let D=await H.json();f.textContent=(A=D.message)!=null?A:"Thanks! We'll be in touch soon.",D.success&&D.nextPrompt&&await r.sendMessage(String(D.nextPrompt))}catch(H){f.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var nc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Ea=new nc;var Vg=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Eb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Mb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},Ma=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Eb(e),n=Mb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},rc=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:rc(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=rc(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:rc(n.text)}}},Kg=e=>Array.isArray(e)?e.map(t=>String(t)):[],ka=e=>{let t=new Set(Kg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Kg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},m=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let f=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:f,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var kb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Lb=e=>e.map(t=>({...t,streaming:!1})),Pb=e=>e.map(t=>({...t,status:"complete"})),Oi=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?kb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Lb(n.messages):void 0,artifacts:n.artifacts?Pb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Ns=require("partial-json");function Ib(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Rb(e,t){if(!Ib(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Fi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,Ns.parse)(n,Ns.STR|Ns.OBJ),o=Rb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Gg(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _i(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=Zr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Jg(){let e=Fi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Qg(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 $i(e){let t=Qg(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 ji(e){let t=Qg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Wb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ui(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Wb}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,g.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,g.appendChild(v),f.appendChild(g);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 S=[];for(let A=1;A<=5;A++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),H.title=c[A-1],H.dataset.rating=String(A),H.innerHTML=`
|
|
30
|
+
`):""},Ql=(e,t)=>{var n,r,s;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=(s=t.codeBlockTextColor)!=null?s:"var(--persona-text, #171717)"},nb=(e,t)=>{var p,m,f,g,x;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=tb(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?km(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&d.activeTextTemplate?c=Tl(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Tl(n,d.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Ig=(e,t,n)=>{var p;let r=Bs.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",f=xe(r?"chevron-up":"chevron-down",16,m,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Xl=(e,t)=>{var V,ne,Ie,Ue,Ae,Le,_e,ye,De;let n=e.toolCall,r=(V=t==null?void 0:t.toolCall)!=null?V:{},s=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let o=(Ie=(ne=t==null?void 0:t.features)==null?void 0:ne.toolCallDisplay)!=null?Ie:{},a=o.expandable!==!1,i=a&&Bs.has(e.id),{summary:d,previewText:c,isActive:p}=nb(e,t),m=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let x=String((Ue=n.startedAt)!=null?Ue:Date.now()),v=()=>{let ie=y("span","");return ie.setAttribute("data-tool-elapsed",x),ie.textContent=aa(n),ie},M=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(Ae=o.collapsedMode)!=null?Ae:"tool-call",isActive:p,config:t!=null?t:{},elapsed:aa(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(g.textContent=M,f.appendChild(g)):M instanceof HTMLElement?f.appendChild(M):(g.textContent=d,f.appendChild(g));let S=(_e=o.loadingAnimation)!=null?_e:"none",R=r.activeTextTemplate,O=r.completeTextTemplate,k=p?R:O,I=M instanceof HTMLElement,A=(ie,X,re)=>{let ce=re;for(let oe of X){let J=y("span","persona-tool-char");J.style.setProperty("--char-index",String(ce)),J.textContent=oe===" "?"\xA0":oe,ie.appendChild(J),ce++}return ce},H=(ie,X)=>{var J;g.textContent="";let re=((J=n.name)==null?void 0:J.trim())||"tool",ce=Ya(ie,re),oe=0;for(let te of ce){let ze=te.styles.length>0?(()=>{let Q=y("span",te.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(Q),Q})():g;if(te.isDuration&&p)ze.appendChild(v());else{let Q=te.isDuration?aa(n):te.text;X?oe=A(ze,Q,oe):ze.appendChild(document.createTextNode(Q))}}};if(!I)if(p&&S!=="none"){let ie=(ye=r.loadingAnimationDuration)!=null?ye:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),k&&H(k,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)H(k,!0);else{let X=g.textContent||d;g.textContent="",A(g,X,0)}}else k&&H(k,!1);let D=null;if(a){D=y("div","persona-flex persona-items-center");let ie=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=xe(i?"chevron-up":"chevron-down",16,ie,2);X?D.appendChild(X):D.textContent=i?"Hide":"Show";let re=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(D),m.append(f,re)}else m.append(f);let N=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let ie=(De=r.renderCollapsedPreview)==null?void 0:De.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});eb(N,ie)||(N.textContent=c),N.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,N),s;let L=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",r.contentBackgroundColor&&(L.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(L.style.color=r.contentTextColor),r.contentPaddingX&&(L.style.paddingLeft=r.contentPaddingX,L.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(L.style.paddingTop=r.contentPaddingY,L.style.paddingBottom=r.contentPaddingY),n.name){let ie=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ie.style.color=r.contentTextColor:r.headerTextColor&&(ie.style.color=r.headerTextColor),ie.textContent=n.name,L.appendChild(ie)}if(n.args!==void 0){let ie=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",Ql(re,r),re.textContent=Ss(n.args),ie.append(X,re),L.appendChild(ie)}if(n.chunks&&n.chunks.length){let ie=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",Ql(re,r),re.textContent=n.chunks.join(""),ie.append(X,re),L.appendChild(ie)}if(n.status==="complete"&&n.result!==void 0){let ie=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",Ql(re,r),re.textContent=Ss(n.result),ie.append(X,re),L.appendChild(ie)}if(n.status==="complete"&&typeof n.duration=="number"){let ie=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ie.style.color=r.contentTextColor),ie.textContent=`Duration: ${n.duration}ms`,L.appendChild(ie)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let ie=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=xe(i?"chevron-up":"chevron-down",16,ie,2);X?D.appendChild(X):D.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),s.append(m,N,L),s};var Wi=new Map,rb=e=>{let n=(e.startsWith(Vr)?e.slice(Vr.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)},Rg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Wg=(e,t)=>{var r,s,o;let n=(s=(r=Rg(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=Wi.get(e))!=null?o:n==="expanded"},Hg=(e,t,n)=>{var a,i;let r=Rg(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=xe(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},Bg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=Wg(e,n);Hg(r,o,n),s.style.display=o?"":"none"};var Hi=(e,t)=>{var H,D,N,L,U,V,ne,Ie,Ue,Ae,Le,_e,ye,De,ie;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(H=r==null?void 0:r.backgroundColor)!=null?H:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(D=r==null?void 0:r.borderColor)!=null?D:"var(--persona-approval-border, #fef08a)",o.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(N=r==null?void 0:r.titleColor)!=null?N:"currentColor",p=xe(d,20,c,2);p&&i.appendChild(p);let m=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",f.appendChild(g),!s){let X=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),f.appendChild(X)}m.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Vr)?gl(n.toolName):void 0,M=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),S=!n.toolName,R=M||(S?n.description:`The assistant wants to use \u201C${v!=null?v:rb(n.toolName)}\u201D.`),O=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(O.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(O.style.color=r.descriptionColor),O.textContent=R,m.appendChild(O),n.reason){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let re=y("span","persona-font-medium");re.textContent=`${(V=r==null?void 0:r.reasonLabel)!=null?V:"Agent's stated reason:"} `,X.appendChild(re),X.appendChild(document.createTextNode(n.reason)),m.appendChild(X)}let k=(ne=r==null?void 0:r.detailsDisplay)!=null?ne:"collapsed",I=!!n.description&&!S,A=I||!!n.parameters;if(k!=="hidden"&&A){let X=Wg(e.id,t),re=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");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let ce=y("span");ce.setAttribute("data-approval-details-label","true");let oe=y("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),re.append(ce,oe),Hg(re,X,t),m.appendChild(re);let J=y("div");if(J.setAttribute("data-approval-details","true"),J.style.display=X?"":"none",I){let te=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=n.description,J.appendChild(te)}if(n.parameters){let te=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&&(te.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=Ss(n.parameters),J.appendChild(te)}m.appendChild(J)}if(s){let X=y("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let re=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");re.type="button",re.style.backgroundColor=(Ie=r==null?void 0:r.approveButtonColor)!=null?Ie:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(Ue=r==null?void 0:r.approveButtonTextColor)!=null?Ue:"#ffffff",re.setAttribute("data-approval-action","approve");let ce=xe("shield-check",14,(Ae=r==null?void 0:r.approveButtonTextColor)!=null?Ae:"#ffffff",2);ce&&(ce.style.marginRight="4px",re.appendChild(ce));let oe=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");re.appendChild(oe);let J=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");J.type="button",J.style.backgroundColor=(_e=r==null?void 0:r.denyButtonColor)!=null?_e:"transparent",J.style.color=(ye=r==null?void 0:r.denyButtonTextColor)!=null?ye:"var(--persona-feedback-error, #dc2626)",J.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,J.setAttribute("data-approval-action","deny");let te=xe("shield-x",14,(De=r==null?void 0:r.denyButtonTextColor)!=null?De:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",J.appendChild(te));let ze=document.createTextNode((ie=r==null?void 0:r.denyLabel)!=null?ie:"Deny");J.appendChild(ze),X.append(re,J),m.appendChild(X)}return a.append(i,m),o.appendChild(a),o};var Dg=e=>{let t=[],n=null;return{buttons:t,render:(s,o,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!s||!s.length||!p&&(i!=null?i:o?o.getMessages():[]).some(M=>M.role==="user"))return;let m=document.createDocumentFragment(),f=o?o.isStreaming():!1,g=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(s.forEach(x=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=x,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),o.sendMessage(x))}),m.appendChild(v),t.push(v)}),e.appendChild(m),p){let x=JSON.stringify(s);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var Sa=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 Aa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var ob=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),sb=new Set(["step_start","execution_start"]),ab=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),ib=new Set(["step_complete","agent_turn_complete"]),lb=new Set(["flow_complete","agent_complete"]),Ng=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Fg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ts=(e,t)=>{let n=e[t];return Fg(n)?n:void 0};function Yl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Bi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function cb(e,t){return typeof t.type=="string"?t.type:e}function db(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function 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 Og(e){var r,s,o,a,i;let t=ts(e,"result"),n=[ts(e,"tokens"),ts(e,"totalTokens"),t?ts(t,"tokens"):void 0,ts(e,"usage"),t?ts(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(s=(r=Yn(d.output))!=null?r:Yn(d.outputTokens))!=null?s:Yn(d.completionTokens);if(c!==void 0)return c}return(i=(o=Yn(e.outputTokens))!=null?o:Yn(e.completionTokens))!=null?i:t?(a=Yn(t.outputTokens))!=null?a:Yn(t.completionTokens):void 0}function ub(e){var n,r,s,o,a;let t=ts(e,"result");return(a=(s=(r=(n=Yn(e.executionTime))!=null?n:Yn(e.executionTimeMs))!=null?r:Yn(e.execution_time))!=null?s:Yn(e.duration))!=null?a:t?(o=Yn(t.executionTime))!=null?o:Yn(t.executionTimeMs):void 0}function mb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=mb){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Bi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!Fg(n)){Ng.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=cb(t,n),s=this.now();if(ob.has(r)){this.startRun(s);return}if(sb.has(r)){this.run||this.startRun(s);return}if(ab.has(r)){if(!pb(r,n))return;let a=db(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Yl(i.visibleCharCount),c=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Bi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(ib.has(r)){if(!this.run)return;let a=this.run,i=Og(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Yl(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:Bi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(lb.has(r)){if(!this.run)return;let a=this.run,i=Og(n),d=i!=null?i:a.exactOutputTokens+Yl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:Bi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(Ng.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=ub(n);return o!=null?o:r-t.startedAt}};function Ds(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var gb={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)"}},fb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},hb=["flowName","stepName","reasoningText","text","name","tool","toolName"],yb=100;function bb(e,t){let n={...gb,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return fb}function xb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function vb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function wb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Cb(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 Sb(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 Ab(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Tb(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 Eb(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Zl(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ds(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(m()),c;function m(){var V,ne;let g=y("div",""),x=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=xe(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.appendChild(M);let S=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=(V=r.timestampFormat)!=null?V:"relative";S.textContent=R==="relative"?xb(e.timestamp,n):vb(e.timestamp);let O=null;r.showSequenceNumbers!==!1&&(O=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),O.textContent=String(t+1));let k=bb(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 A=(ne=r.descriptionFields)!=null?ne:hb,H=wb(e.payload,A),D=null;H&&(D=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),D.textContent=H);let N=y("div","persona-flex-1 persona-min-w-0"),L=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),U=xe("clipboard","12px","currentColor",1.5);return U&&L.appendChild(U),L.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Cb(Sb(e)),L.innerHTML="";let Ue=xe("check","12px","currentColor",1.5);Ue&&L.appendChild(Ue),setTimeout(()=>{L.innerHTML="";let Ae=xe("clipboard","12px","currentColor",1.5);Ae&&L.appendChild(Ae)},1500)}),x.appendChild(v),x.appendChild(S),O&&x.appendChild(O),x.appendChild(I),D&&x.appendChild(D),x.appendChild(N),x.appendChild(L),g.appendChild(x),d&&g.appendChild(Eb(e,a,i)),g}}function _g(e){var x,v,M,S,R;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",m=(R=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?R:{},f=o.find(O=>O.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let O=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(O)return{element:O,update:()=>{},destroy:()=>{}}}return g();function g(){let O=m.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ds(k,O==null?void 0:O.panel);let I=[],A="",H="",D=null,N=[],L={},U=0,V=yi(),ne=0,Ie=0,Ue=!1,Ae=null,Le=!1,_e=0,ye=new Set,De=new Map,ie="",X="",re=null,ce,oe,J,te,ze,Q=null,le=null,We=null;function we(){let K=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ue=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");Ds(ue,O==null?void 0:O.headerBar);let Me=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Me.textContent="Events",ce=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"),ce.textContent="0",a){le=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let Zn=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Zn.textContent="Throughput",Q=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"),Q.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 Sn=le,tn=We,In=()=>{if(!tn.textContent)return;let vt=Sn.getBoundingClientRect(),Nn=K.getBoundingClientRect();tn.style.left=`${vt.left-Nn.left}px`,tn.style.top=`${vt.bottom-Nn.top+4}px`,tn.style.display="block"},vr=()=>{tn.style.display="none"};le.addEventListener("mouseenter",In),le.addEventListener("mouseleave",vr),le.appendChild(Zn),le.appendChild(Q)}let xt=y("div","persona-flex-1");oe=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 Zt=y("option","");Zt.value="",Zt.textContent="All events",oe.appendChild(Zt),J=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"),J.type="button",J.title="Copy All";let mn=xe("clipboard-copy","12px","currentColor",1.5);mn&&J.appendChild(mn);let Ht=y("span","persona-text-xs");Ht.textContent="Copy All",J.appendChild(Ht),ue.appendChild(Me),ue.appendChild(ce),le&&ue.appendChild(le),ue.appendChild(xt),ue.appendChild(oe),ue.appendChild(J);let rt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ds(rt,O==null?void 0:O.searchBar);let Wt=xe("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");Wt&&ct.appendChild(Wt),te=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"),Ds(te,O==null?void 0:O.searchInput),te.type="text",te.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let Gt=xe("x","12px","currentColor",2);return Gt&&ze.appendChild(Gt),rt.appendChild(ct),rt.appendChild(te),rt.appendChild(ze),K.appendChild(ue),K.appendChild(rt),We&&K.appendChild(We),K}let Ye,Ge=o.find(K=>K.renderEventStreamToolbar);if(Ge!=null&&Ge.renderEventStreamToolbar&&s){let K=Ge.renderEventStreamToolbar({config:s,defaultRenderer:()=>we(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ue=>{A=ue,It(),yn()},onSearchChange:ue=>{H=ue,It(),yn()}});Ye=K!=null?K:we()}else Ye=we();let Oe=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";function de(){if(!a||!Q||!le)return;let K=a();Q.textContent=Ab(K);let ue=Tb(K);We&&(We.textContent=ue,ue||(We.style.display="none")),ue?le.setAttribute("aria-label",ue):le.removeAttribute("aria-label")}let tt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let pe=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");Ds(pe,O==null?void 0:O.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Ce=xe(c,"14px","currentColor",2);Ce&&pe.appendChild(Ce);let Ve=y("span","");Ve.textContent=p,pe.appendChild(Ve);let Pt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Pt.style.display="none",tt.appendChild(Y),tt.appendChild(Pt),tt.appendChild(pe),k.setAttribute("tabindex","0"),k.appendChild(Ye),k.appendChild(Oe),k.appendChild(tt);function Te(){let K=t.getAll(),ue={};for(let Ht of K)ue[Ht.type]=(ue[Ht.type]||0)+1;let Me=Object.keys(ue).sort(),xt=Me.length!==N.length||!Me.every((Ht,rt)=>Ht===N[rt]),Zt=!xt&&Me.some(Ht=>ue[Ht]!==L[Ht]),en=K.length!==Object.values(L).reduce((Ht,rt)=>Ht+rt,0);if(!xt&&!Zt&&!en||(N=Me,L=ue,!oe))return;let mn=oe.value;if(oe.options[0].textContent="All events",xt){for(;oe.options.length>1;)oe.remove(1);for(let Ht of Me){let rt=y("option","");rt.value=Ht,rt.textContent=`${Ht} (${ue[Ht]||0})`,oe.appendChild(rt)}mn&&Me.includes(mn)?oe.value=mn:mn&&(oe.value="",A="")}else for(let Ht=1;Ht<oe.options.length;Ht++){let rt=oe.options[Ht];rt.textContent=`${rt.value} (${ue[rt.value]||0})`}}function ge(){let K=t.getAll();if(A&&(K=K.filter(ue=>ue.type===A)),H){let ue=H.toLowerCase();K=K.filter(Me=>Me.type.toLowerCase().includes(ue)||Me.payload.toLowerCase().includes(ue))}return K}function hn(){return A!==""||H!==""}function It(){U=0,ne=0,V.resume(),pe.style.display="none"}function sn(K){ye.has(K)?ye.delete(K):ye.add(K),re=K;let ue=Y.scrollTop,Me=V.isFollowing();Le=!0,V.pause(),yn(),Y.scrollTop=ue,Me&&V.resume(),Le=!1}function xr(){return Yo(Y,50)}function yn(){Ie=Date.now(),Ue=!1,de(),Te();let K=t.getEvictedCount();K>0?(Oe.textContent=`${K.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",I=ge();let ue=I.length,Me=t.getSize()>0;ce&&(ce.textContent=String(t.getSize())),ue===0&&Me&&hn()?(Pt.textContent=H?`No events matching '${H}'`:"No events matching filter",Pt.style.display="",Y.style.display="none"):(Pt.style.display="none",Y.style.display=""),J&&(J.title=hn()?`Copy Filtered (${ue})`:"Copy All"),d&&!V.isFollowing()&&ue>U&&(ne+=ue-U,Ve.textContent=p?`${p}${ne>0?` (${ne})`:""}`:"",pe.style.display=""),U=ue;let xt=t.getAll(),Zt=xt.length>0?xt[0].timestamp:0,en=new Set(I.map(rt=>rt.id));for(let rt of ye)en.has(rt)||ye.delete(rt);let mn=A!==ie||H!==X,Ht=De.size===0&&I.length>0;if(mn||Ht||I.length===0){Y.innerHTML="",De.clear();let rt=document.createDocumentFragment();for(let Wt=0;Wt<I.length;Wt++){let ct=Zl(I[Wt],Wt,Zt,m,ye,sn,o,s);De.set(I[Wt].id,ct),rt.appendChild(ct)}Y.appendChild(rt),ie=A,X=H,re=null}else{if(re!==null){let Wt=De.get(re);if(Wt&&Wt.parentNode===Y){let ct=I.findIndex(Gt=>Gt.id===re);if(ct>=0){let Gt=Zl(I[ct],ct,Zt,m,ye,sn,o,s);Y.insertBefore(Gt,Wt),Wt.remove(),De.set(re,Gt)}}re=null}let rt=new Set(I.map(Wt=>Wt.id));for(let[Wt,ct]of De)rt.has(Wt)||(ct.remove(),De.delete(Wt));for(let Wt=0;Wt<I.length;Wt++){let ct=I[Wt];if(!De.has(ct.id)){let Gt=Zl(ct,Wt,Zt,m,ye,sn,o,s);De.set(ct.id,Gt),Y.appendChild(Gt)}}}V.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function Ke(){if(Date.now()-Ie>=yb){Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),yn();return}Ue||(Ue=!0,Ae=requestAnimationFrame(()=>{Ae=null,yn()}))}let E=(K,ue)=>{if(!J)return;J.innerHTML="";let Me=xe(K,"12px","currentColor",1.5);Me&&J.appendChild(Me);let xt=y("span","persona-text-xs");xt.textContent="Copy All",J.appendChild(xt),setTimeout(()=>{J.innerHTML="";let Zt=xe("clipboard-copy","12px","currentColor",1.5);Zt&&J.appendChild(Zt);let en=y("span","persona-text-xs");en.textContent="Copy All",J.appendChild(en),J.disabled=!1},ue)},me=async()=>{if(J){J.disabled=!0;try{let K;hn()?K=I:n?(K=await n(),K.length===0&&(K=t.getAll())):K=t.getAll();let ue=K.map(Me=>{try{return JSON.parse(Me.payload)}catch{return Me.payload}});await navigator.clipboard.writeText(JSON.stringify(ue,null,2)),E("check",1500)}catch{E("x",1500)}}},ke=()=>{oe&&(A=oe.value,It(),yn())},Ee=()=>{!te||!ze||(ze.style.display=te.value?"":"none",D&&clearTimeout(D),D=setTimeout(()=>{H=te.value,It(),yn()},150))},Re=()=>{!te||!ze||(te.value="",H="",ze.style.display="none",D&&clearTimeout(D),It(),yn())},nt=()=>{if(Le)return;let K=Y.scrollTop,{action:ue,nextLastScrollTop:Me}=bi({following:V.isFollowing(),currentScrollTop:K,lastScrollTop:_e,nearBottom:xr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_e=Me,ue==="resume"?(V.resume(),ne=0,pe.style.display="none"):ue==="pause"&&(V.pause(),d&&(Ve.textContent=p,pe.style.display=""))},Qe=K=>{let ue=xi({following:V.isFollowing(),deltaY:K.deltaY,nearBottom:xr(),resumeWhenNearBottom:!0});ue==="pause"?(V.pause(),d&&(Ve.textContent=p,pe.style.display="")):ue==="resume"&&(V.resume(),ne=0,pe.style.display="none")},ut=()=>{d&&(Y.scrollTop=Y.scrollHeight,V.resume(),ne=0,pe.style.display="none")},Rt=K=>{let ue=K.target;if(!ue||ue.closest("button"))return;let Me=ue.closest("[data-event-id]");if(!Me)return;let xt=Me.getAttribute("data-event-id");xt&&sn(xt)},q=K=>{if((K.metaKey||K.ctrlKey)&&K.key==="f"){K.preventDefault(),te==null||te.focus(),te==null||te.select();return}K.key==="Escape"&&(te&&document.activeElement===te?(Re(),te.blur(),k.focus()):r&&r())};J&&J.addEventListener("click",me),oe&&oe.addEventListener("change",ke),te&&te.addEventListener("input",Ee),ze&&ze.addEventListener("click",Re),Y.addEventListener("scroll",nt),Y.addEventListener("wheel",Qe,{passive:!0}),Y.addEventListener("click",Rt),pe.addEventListener("click",ut),k.addEventListener("keydown",q);function at(){D&&clearTimeout(D),Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),Ue=!1,De.clear(),J&&J.removeEventListener("click",me),oe&&oe.removeEventListener("change",ke),te&&te.removeEventListener("input",Ee),ze&&ze.removeEventListener("click",Re),Y.removeEventListener("scroll",nt),Y.removeEventListener("wheel",Qe),Y.removeEventListener("click",Rt),pe.removeEventListener("click",ut),k.removeEventListener("keydown",q)}return{element:k,update:Ke,destroy:at}}}function $g(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(g)}else m.textContent=a;if(c.append(p,m),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var jg=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>$g(e,t)});if(p)return p}return $g(e,t)};var ec=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)})}},Zr=new ec;Zr.register("PersonaArtifactCard",jg);function Mb(e){var s;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Ug(e,t){var oe,J,te,ze;let n=(J=(oe=e.features)==null?void 0:oe.artifacts)==null?void 0:J.layout,s=((te=n==null?void 0:n.toolbarPreset)!=null?te:"default")==="document",o=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?zo(e.markdown):null,i=bs(e.sanitize),d=Q=>{let le=a?a(Q):Rr(Q);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};c&&c.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let m=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let f=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let v="rendered",M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),R=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),O=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,A=n==null?void 0:n.documentToolbarCopyMenuItems,H=!!(I&&A&&A.length>0),D=null,N,L=null,U=null;if(s&&(k||I)&&!H){if(N=k?wa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let Q=xe("chevron-down",14,"currentColor",2);Q&&N.appendChild(Q)}}else s&&H?(D=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=k?wa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=qt({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"}}),D.append(N,L)):s?N=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=qt({icon:"copy",label:"Copy"});let V=s?qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):qt({icon:"refresh-cw",label:"Refresh"}),ne=s?qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):qt({icon:"x",label:"Close"}),Ie=()=>{var Ye,Ge,Oe;let Q=(Ye=De.find(de=>de.id===ie))!=null?Ye:De[De.length-1],le=(Ge=Q==null?void 0:Q.id)!=null?Ge:null,We=(Q==null?void 0:Q.artifactType)==="markdown"&&(Oe=Q.markdown)!=null?Oe:"",we=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:We,jsonPayload:we,id:le}},Ue=async()=>{var Ye;let{markdown:Q,jsonPayload:le}=Ie(),We=(Ye=De.find(Ge=>Ge.id===ie))!=null?Ye:De[De.length-1],we=(We==null?void 0:We.artifactType)==="markdown"?Q:We?le:"";try{await navigator.clipboard.writeText(we)}catch{}};if(N.addEventListener("click",async()=>{let Q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Q&&H){let{markdown:le,jsonPayload:We,id:we}=Ie();try{await Q({actionId:"primary",artifactId:we,markdown:le,jsonPayload:We})}catch{}return}await Ue()}),L&&(A!=null&&A.length)){let Q=()=>{var We;return(We=m.closest("[data-persona-root]"))!=null?We:document.body},le=()=>{U=Mo({items:A.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:we,jsonPayload:Ye,id:Ge}=Ie(),Oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:We,artifactId:Ge,markdown:we,jsonPayload:Ye}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(we):We==="json"||We==="source"?await navigator.clipboard.writeText(Ye):await navigator.clipboard.writeText(we||Ye)}catch{}},anchor:D!=null?D:L,position:"bottom-right",portal:Q()})};m.isConnected?le():requestAnimationFrame(le),L.addEventListener("click",We=>{We.stopPropagation(),U==null||U.toggle()})}V.addEventListener("click",async()=>{var Q;try{await((Q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Q.call(n))}catch{}re()}),ne.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let Ae=()=>{s&&(S.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};S.addEventListener("click",()=>{v="rendered",Ae(),re()}),R.addEventListener("click",()=>{v="source",Ae(),re()});let Le=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),M.append(S,R),D?O.append(D,V,ne):O.append(N,V,ne),f.append(M,Le,O),Ae()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let _e=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"),ye=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(_e.style.paddingLeft=o,_e.style.paddingRight=o,ye.style.padding=o),m.appendChild(f),m.appendChild(_e),m.appendChild(ye);let De=[],ie=null,X=!1,re=()=>{var we,Ye,Ge,Oe;let Q=s&&De.length<=1;_e.classList.toggle("persona-hidden",Q),_e.replaceChildren();for(let de of De){let tt=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");tt.type="button",tt.textContent=de.title||de.id.slice(0,8),de.id===ie&&tt.classList.add("persona-bg-persona-container","persona-border-persona-border"),tt.addEventListener("click",()=>t.onSelect(de.id)),_e.appendChild(tt)}ye.replaceChildren();let le=ie&&De.find(de=>de.id===ie)||De[De.length-1];if(!le)return;if(s){let de=le.artifactType==="markdown"?"MD":(we=le.component)!=null?we:"Component",Y=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Y} \xB7 ${de}`}else g.textContent="Artifacts";if(le.artifactType==="markdown"){if(s&&v==="source"){let tt=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");tt.textContent=(Ye=le.markdown)!=null?Ye:"",ye.appendChild(tt);return}let de=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");de.innerHTML=d((Ge=le.markdown)!=null?Ge:""),ye.appendChild(de);return}let We=le.component?Zr.get(le.component):void 0;if(We){let tt={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=We((Oe=le.props)!=null?Oe:{},tt);if(Y){ye.appendChild(Y);return}}catch{}}ye.appendChild(Mb(le))},ce=()=>{var le;let Q=De.length>0;if(m.classList.toggle("persona-hidden",!Q),c){let We=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ye=((le=We==null?void 0:We.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&Ye&&X?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(Q){var le,We,we;De=Q.artifacts,ie=(we=(We=Q.selectedId)!=null?We:(le=Q.artifacts[Q.artifacts.length-1])==null?void 0:le.id)!=null?we:null,De.length>0&&(X=!0),re(),ce()},setMobileOpen(Q){X=Q,!Q&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ce()}}}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 qg(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!cr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function 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 Di(e,t){var d,c,p,m,f,g,x,v,M,S;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),qg(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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=(S=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),qg(e,t)}var zg=["panel","seamless"];function Ni(e,t){var i,d,c,p,m,f;for(let g of zg)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!cr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",s=zg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Vg(e,t){var n,r,s;return!t||!cr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Lb(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 Pb(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 Ib(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Rb(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Kg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Gg(e,t,n,r,s,o){let a=Lb(s,200),i=Rb(t,n,r,200);i=Math.max(a,i);let d=Pb(o);return d!==null&&(i=Math.min(i,d)),Ib(e,a,i)}var Jg={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"}},tc=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,M;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=Jg[a])!=null?v:Jg.init;o.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let S=y("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var A,H;let R=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${S.name}`;let O=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");O.textContent=S.label,R.appendChild(O);let k=(A=S.type)!=null?A:"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}-${S.name}`,I.name=S.name,I.placeholder=(H=S.placeholder)!=null?H:"",S.required&&(I.required=!0),R.appendChild(I),p.appendChild(R)});let m=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(M=i.submitLabel)!=null?M:"Submit",m.appendChild(f),m.appendChild(g),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async S=>{var I,A;S.preventDefault();let R=(I=n.formEndpoint)!=null?I:"/form",O=new FormData(p),k={};O.forEach((H,D)=>{k[D]=H}),k.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let H=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let D=await H.json();f.textContent=(A=D.message)!=null?A:"Thanks! We'll be in touch soon.",D.success&&D.nextPrompt&&await r.sendMessage(String(D.nextPrompt))}catch(H){f.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var nc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Ea=new nc;var Qg=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Wb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Hb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},Ma=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Wb(e),n=Hb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},rc=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:rc(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=rc(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:rc(n.text)}}},Xg=e=>Array.isArray(e)?e.map(t=>String(t)):[],ka=e=>{let t=new Set(Xg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Xg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},m=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let f=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:f,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Bb=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}},Db=e=>e.map(t=>({...t,streaming:!1})),Nb=e=>e.map(t=>({...t,status:"complete"})),Oi=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Bb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Db(n.messages):void 0,artifacts:n.artifacts?Nb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Ns=require("partial-json");function Ob(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Fb(e,t){if(!Ob(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Fi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,Ns.parse)(n,Ns.STR|Ns.OBJ),o=Fb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Yg(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _i(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=Zr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Zg(){let e=Fi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ef(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 $i(e){let t=ef(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 ji(e){let t=ef(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 _b=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ui(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=_b}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,g.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,g.appendChild(v),f.appendChild(g);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 S=[];for(let A=1;A<=5;A++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),H.title=c[A-1],H.dataset.rating=String(A),H.innerHTML=`
|
|
29
31
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
30
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>
|
|
31
33
|
</svg>
|
|
32
|
-
`,H.addEventListener("click",()=>{m=A,S.forEach((D,N)=>{let L=N<A;D.classList.toggle("selected",L),D.setAttribute("aria-checked",N===A-1?"true":"false")})}),S.push(H),M.appendChild(H)}f.appendChild(M);let R=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),A.appendChild(R),f.appendChild(A)}let O=document.createElement("div");O.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(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=(R==null?void 0:R.value.trim())||void 0;await t(m,A),p.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),O.appendChild(k),O.appendChild(I),f.appendChild(O),p.appendChild(f),p}function qi(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,x.appendChild(M),g.appendChild(x);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,R.appendChild(O),R.appendChild(k);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let U=0;U<=10;U++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${U} out of 10`),V.textContent=String(U),V.dataset.rating=String(U),U<=6?V.classList.add("persona-feedback-detractor"):U<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=U,A.forEach((ne,Ie)=>{ne.classList.toggle("selected",Ie===U),ne.setAttribute("aria-checked",Ie===U?"true":"false")})}),A.push(V),I.appendChild(V)}S.appendChild(R),S.appendChild(I),g.appendChild(S);let H=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=o,H.rows=3,H.setAttribute("aria-label","Additional comments"),U.appendChild(H),g.appendChild(U)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{n==null||n(),m.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let U=(H==null?void 0:H.value.trim())||void 0;await t(f,U),m.remove()}catch(U){L.disabled=!1,L.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),D.appendChild(N),D.appendChild(L),g.appendChild(D),m.appendChild(g),m}var Os="persona-chat-history",Hb=30*1e3,Bb={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Db(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Bb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function zi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Nb(e){var t,n,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Ob(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var oc=e=>!e||typeof e!="object"?{}:{...e},Xg=e=>e.map(t=>({...t,streaming:!1})),Yg=(e,t,n)=>{let r=e!=null&&e.markdown?zo(e.markdown):null,s=bs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var p,m,f;let a=(p=o.text)!=null?p:"",i=(m=o.message.rawContent)!=null?m:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d=qo()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...o,text:a,raw:(f=i!=null?i:o.text)!=null?f:""});c=s?s(g):g}else if(r){let g=r(a);c=s&&d?s(g):g}else c=Rr(a);return c}};function Zg(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=xe(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=y("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Vi=(e,t,n)=>{var Jc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Sd,Ad,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd;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=pi(t),s=Ea.getForInstance(r.plugins);r.components&&Zr.registerAll(r.components);let o=Vg(),i=r.persistState===!1?null:(Jc=r.storageAdapter)!=null?Jc:Oi(),d={},c=null,p=!1,m=l=>{if(r.onStateLoaded)try{let u=r.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:b}=u;return b&&(p=!0),h}return u}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return m(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=m(u);h.metadata&&(d=oc(h.metadata)),(Qc=h.messages)!=null&&Qc.length&&(r={...r,initialMessages:h.messages}),(Xc=h.artifacts)!=null&&Xc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Yc=h.selectedArtifactId)!=null?Yc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(Zc=l.messages)!=null&&Zc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let f=()=>d,g=l=>{var h;d=(h=l({...d}))!=null?h:{},co()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ma],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],M=ka({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let S=(td=(ed=r.launcher)==null?void 0:ed.enabled)!=null?td:!0,R=(rd=(nd=r.launcher)==null?void 0:nd.autoExpand)!=null?rd:!1,O=(od=r.autoFocusInput)!=null?od:!1,k=R,I=S,A=(ad=(sd=r.layout)==null?void 0:sd.header)==null?void 0:ad.layout,H=!1,D=()=>Eo(r),N=()=>S||D(),L=D()?!1:S?R:!0,U=!1,V=null,ne=()=>{U=!0,V&&clearTimeout(V),V=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Ie=Yg(r,M,ne),Ue=(ld=(id=r.features)==null?void 0:id.showReasoning)!=null?ld:!0,Ae=(dd=(cd=r.features)==null?void 0:cd.showToolCalls)!=null?dd:!0,Le=(ud=(pd=r.features)==null?void 0:pd.showEventStreamToggle)!=null?ud:!1,_e=(gd=(md=r.features)==null?void 0:md.scrollToBottom)!=null?gd:{},ye=(hd=(fd=r.features)==null?void 0:fd.scrollBehavior)!=null?hd:{},ie=`${(bd=typeof r.persistState=="object"?(yd=r.persistState)==null?void 0:yd.keyPrefix:void 0)!=null?bd:"persona-"}event-stream`,X=Le?new Aa(ie):null,re=(wd=(vd=(xd=r.features)==null?void 0:xd.eventStream)==null?void 0:vd.maxEvents)!=null?wd:2e3,ce=Le?new Sa(re,X):null,oe=Le?new Ta:null,J=null,te=!1,ze=null,Q=0;X==null||X.open().then(()=>ce==null?void 0:ce.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let le={onCopy:l=>{var u,h;o.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;o.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},We=(Cd=r.statusIndicator)!=null?Cd:{},we=l=>{var u,h,b,T;return l==="idle"?(u=We.idleText)!=null?u:wn.idle:l==="connecting"?(h=We.connectingText)!=null?h:wn.connecting:l==="connected"?(b=We.connectedText)!=null?b:wn.connected:l==="error"?(T=We.errorText)!=null?T:wn.error:wn[l]};function Ye(l,u,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=u,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=u}let Ge=Cg({config:r,showClose:N()}),{wrapper:Oe,panel:de,pillRoot:tt}=Ge.shell,Y=Ge.panelElements,{container:pe,body:Ce,messagesWrapper:Ve,suggestions:Pt,textarea:Te,sendButton:ge,sendButtonWrapper:hn,composerForm:It,statusText:sn,introTitle:xr,introSubtitle:yn,closeButton:Ke,iconHolder:E,headerTitle:me,headerSubtitle:ke,header:Ee,footer:Re,actionsRow:nt,leftActions:Qe,rightActions:ut}=Y,Rt=Y.setSendButtonMode,q=Y.micButton,at=Y.micButtonWrapper,K=Y.attachmentButton,ue=Y.attachmentButtonWrapper,Me=Y.attachmentInput,xt=Y.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Ce.classList.add("persona-relative");let Zt=12,en=()=>{var l;return(l=_e.label)!=null?l:""},mn=()=>{var l;return(l=_e.iconName)!=null?l:"arrow-down"},Ht=()=>_e.enabled!==!1,rt=()=>{var l;return(l=ye.mode)!=null?l:"follow"},Wt=()=>{var l;return(l=ye.anchorTopOffset)!=null?l:16},ct=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");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let Gt=y("span","persona-flex persona-items-center"),Zn=y("span",""),Sn=y("span","");Sn.setAttribute("data-persona-scroll-to-bottom-count",""),Sn.style.display="none",ct.append(Gt,Zn,Sn),pe.appendChild(ct);let tn=y("div","persona-stream-anchor-spacer");tn.setAttribute("aria-hidden","true"),tn.setAttribute("data-persona-anchor-spacer",""),tn.style.flexShrink="0",tn.style.pointerEvents="none",tn.style.height="0px",Ce.appendChild(tn);let In=()=>{let u=Re.style.display==="none"?0:Re.offsetHeight;ct.style.bottom=`${u+Zt}px`};In();let vr=()=>{let l=!!en();ct.setAttribute("aria-label",en()||"Jump to latest"),ct.title=en(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Gt.innerHTML="";let u=xe(mn(),"14px","currentColor",2);u?(Gt.appendChild(u),Gt.style.display=""):Gt.style.display="none",Zn.textContent=en(),Zn.style.display=l?"":"none"};vr();let vt=null,Nn=null,wr=s.find(l=>l.renderHeader);if(wr!=null&&wr.renderHeader){let l=wr.renderHeader({config:r,defaultRenderer:()=>{let u=Yr({config:r,showClose:N()});return Zo(pe,u,r),u.header},onClose:()=>$t(!1,"user")});if(l){let u=pe.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Ee=l,Ge.header.element=l)}}let Br=()=>{var u,h,b,T;if(!ce)return;if(te=!0,!J&&ce&&(J=Dg({buffer:ce,getFullHistory:()=>ce.getAllFromStore(),onClose:()=>dr(),config:r,plugins:s,getThroughput:()=>{var W;return(W=oe==null?void 0:oe.getMetric())!=null?W:{status:"idle"}}})),J&&(Ce.style.display="none",(u=Re.parentNode)==null||u.insertBefore(J.element,Re),J.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let W=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;W&&W.split(/\s+/).forEach(z=>z&&yt.classList.add(z))}let l=()=>{if(!te)return;let W=Date.now();W-Q>=200&&(J==null||J.update(),Q=W),ze=requestAnimationFrame(l)};Q=0,ze=requestAnimationFrame(l),Ze(),o.emit("eventStream:opened",{timestamp:Date.now()})},dr=()=>{var l,u,h;if(te){if(te=!1,J&&J.element.remove(),Ce.style.display="",yt){yt.style.boxShadow="";let b=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&yt.classList.remove(T))}ze!==null&&(cancelAnimationFrame(ze),ze=null),Ze(),o.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(Le){let l=(Ad=(Sd=r.features)==null?void 0:Sd.eventStream)==null?void 0:Ad.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=y("button",u),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=xe("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let b=Y.clearChatButtonWrapper,T=Y.closeButtonWrapper,W=b||T;W&&W.parentNode===Ee?Ee.insertBefore(yt,W):Ee.appendChild(yt),yt.addEventListener("click",()=>{te?dr():Br()})}let Lo=l=>{var T,W,z,F,B;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let se=y("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=u.allowedTypes)!=null?z:Qr).join(","),se.multiple=((F=u.maxFiles)!=null?F:4)>1,se.style.display="none",se.setAttribute("aria-label",(B=u.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(se)}},Cr=s.find(l=>l.renderComposer);if(Cr!=null&&Cr.renderComposer){let l=r.composer,u=Cr.renderComposer({config:r,defaultRenderer:()=>Rs({config:r}).footer,onSubmit:h=>{var z;if(!_||_.isStreaming())return;let b=h.trim(),T=(z=vt==null?void 0:vt.hasAttachments())!=null?z:!1;if(!b&&!T)return;Ec();let W;T&&(W=[],W.push(...vt.getContentParts()),b&&W.push(la(b))),_.sendMessage(b,{contentParts:W}),T&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Me==null||Me.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Td=r.voiceRecognition)==null?void 0:Td.enabled)===!0?()=>{Nn==null||Nn()}:void 0});u&&(Ge.replaceComposer(u),Re=Ge.composer.footer)}let Po=l=>{let u=(...ae)=>{for(let Z of ae){let ve=l.querySelector(Z);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");h&&(It=h),b&&(Te=b),T&&(ge=T),W&&(q=W,at=W.parentElement),z&&(sn=z);let F=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Pt=F);let B=u("[data-persona-composer-attachment-button]",".persona-attachment-button");B&&(K=B,ue=B.parentElement),Me=u("[data-persona-composer-attachment-input]",'input[type="file"]'),xt=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(nt=se)};Lo(Re),Po(Re);let Rn=(Pd=(Ed=r.layout)==null?void 0:Ed.contentMaxWidth)!=null?Pd:D()?(Ld=(kd=(Md=r.launcher)==null?void 0:Md.composerBar)==null?void 0:kd.contentMaxWidth)!=null?Ld:"720px":void 0;if(Rn&&(Ve.style.maxWidth=Rn,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),Rn&&It&&!D()&&(It.style.maxWidth=Rn,It.style.marginLeft="auto",It.style.marginRight="auto"),Rn&&Pt&&!D()&&(Pt.style.maxWidth=Rn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Rn&&xt&&!D()&&(xt.style.maxWidth=Rn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),(Id=r.attachments)!=null&&Id.enabled&&Me&&xt){vt=Xo.fromConfig(r.attachments),vt.setPreviewsContainer(xt),Me.addEventListener("change",h=>{let b=h.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,u=Zg(l);pe.appendChild(u)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},u=W=>{switch(W){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Pt;case"composer":return It;case"footer-bottom":return sn;default:return null}},h=(W,z)=>{var F;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ee.insertBefore(z,Ee.firstChild);else if(W==="header-right")Ee.appendChild(z);else{let B=Ee.querySelector(".persona-flex-col");B?(F=B.parentNode)==null||F.insertBefore(z,B.nextSibling):Ee.appendChild(z)}break;case"body-top":{let B=Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(z):Ce.insertBefore(z,Ce.firstChild);break}case"body-bottom":Ce.appendChild(z);break;case"footer-top":Pt.replaceWith(z);break;case"footer-bottom":sn.replaceWith(z);break;default:break}};for(let[W,z]of Object.entries(l))if(z)try{let F=z({config:r,defaultContent:()=>u(W)});F&&h(W,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,F)}})();let to=l=>{var z,F;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Hs.has(T)?Hs.delete(T):Hs.add(T),Eg(T,b);else if(W==="tool")Bs.has(T)?Bs.delete(T):Bs.add(T),Mg(T,b,r);else if(W==="approval"){let B=r.approval!==!1?r.approval:void 0,se=((z=B==null?void 0:B.detailsDisplay)!=null?z:"collapsed")==="expanded",ae=(F=Wi.get(T))!=null?F:se;Wi.set(T,!ae),Ig(T,b,r)}Mr.delete(T)};Ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),to(l))}),Ve.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),to(l))}),Ve.addEventListener("copy",l=>{let{clipboardData:u}=l;if(!u)return;let h=Ve.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let T=b.toString(),W=ng(T);!W||W===T||(u.setData("text/plain",W),l.preventDefault())});let Dr=new Map,no=null,ro="idle",Io={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ro=(l,u)=>{let{icon:h,label:b}=Io[u];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let T=xe(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},oo=()=>{Ve.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{var W;let h=u.closest("[data-actions-for]"),b=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ro(u,b&&b===no?ro:"idle")})};Ve.addEventListener("click",l=>{var z;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let W=h.getAttribute("data-action");if(W==="copy"){let B=_.getMessages().find(se=>se.id===T);if(B&&le.onCopy){let se=B.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=xe("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=xe("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),le.onCopy(B)}}else if(W==="read-aloud")_.toggleReadAloud(T);else if(W==="upvote"||W==="downvote"){let B=((z=Dr.get(T))!=null?z:null)===W,se=W==="upvote"?"thumbs-up":"thumbs-down";if(B){Dr.delete(T),h.classList.remove("persona-message-action-active");let ae=xe(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=W==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ae}"]`);if(Z){Z.classList.remove("persona-message-action-active");let je=xe(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(Z.innerHTML="",Z.appendChild(je))}Dr.set(T,W),h.classList.add("persona-message-action-active");let ve=xe(se,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(st=>st.id===T);Se&&le.onFeedback&&le.onFeedback({type:W,messageId:Se.id,message:Se})}}}),Ve.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",B=_.getMessages().find(ae=>ae.id===T);if(!(B!=null&&B.approval))return;let se=b.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(T,z):_.resolveApproval(B.approval,z)});let Ct=null,On=null,Fn={artifacts:[],selectedId:null},An=!1,At={current:null};Ve.addEventListener("click",l=>{var Z,ve,Fe,Se,st;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(ve=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Fe.call(ve,{type:"download",artifactId:b}))===!0)return;let W=_.getArtifactById(b),z=W==null?void 0:W.markdown,F=(W==null?void 0:W.title)||"artifact";if(!z){let je=h.closest("[data-open-artifact]"),gt=je==null?void 0:je.closest("[data-message-id]"),it=gt==null?void 0:gt.getAttribute("data-message-id");if(it){let Pe=_.getMessages().find(qe=>qe.id===it);if(Pe!=null&&Pe.rawContent)try{let qe=JSON.parse(Pe.rawContent);z=(Se=qe==null?void 0:qe.props)==null?void 0:Se.markdown,F=((st=qe==null?void 0:qe.props)==null?void 0:st.title)||F}catch{}}}if(!z)return;let B=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(B),ae=document.createElement("a");ae.href=se,ae.download=`${F}.md`,ae.click(),URL.revokeObjectURL(se)}),Ve.addEventListener("click",l=>{var W,z,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((F=(z=(W=r.features)==null?void 0:W.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:F.call(z,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),An=!1,_.selectArtifact(b),jn())}),Ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let er=Y.composerOverlay,tr=(l,u,h)=>{var F,B,se,ae;let b=u.trim();if(!b||!At.current)return;let T=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(B=h.values)!=null?B:h.source==="multi"?b.split(", "):[b],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),xo(er,T);let z=At.current.getMessages().find(Z=>{var ve;return((ve=Z.toolCall)==null?void 0:ve.id)===T});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?At.current.resolveAskUserQuestion(z,(ae=h.structured)!=null?ae:b):At.current.sendMessage(b)},_n=l=>{var T;let u=At.current;if(!u)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=u.getMessages().find(W=>{var z;return((z=W.toolCall)==null?void 0:z.id)===h});b&&u.persistAskUserQuestionProgress(b,{answers:za(l,b),currentIndex:ir(l)})},so=l=>Object.entries(l).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Nr=l=>{var T,W,z;if(((W=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let u=ir(l),h=ws(l);if(u>=h-1)return;let b=(z=At.current)==null?void 0:z.getMessages().find(F=>{var B;return((B=F.toolCall)==null?void 0:B.id)===l.getAttribute("data-tool-call-id")});b&&(Va(l,b,r,u+1),_n(l))};er.addEventListener("click",l=>{var W,z,F,B,se,ae,Z,ve,Fe,Se,st,je,gt,it;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let He=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),xo(er,He);let Pe=(z=At.current)==null?void 0:z.getMessages().find(qe=>{var Je;return((Je=qe.toolCall)==null?void 0:Je.id)===He});(F=Pe==null?void 0:Pe.agentMetadata)!=null&&F.awaitingLocalTool&&((B=At.current)==null||B.markAskUserQuestionResolved(Pe),(se=At.current)==null||se.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(T==="pick"){let He=h.getAttribute("data-option-label");if(!He)return;let Pe=b.getAttribute("data-multi-select")==="true",qe=bo(b);if(qe&&Pe){let Je=Vo(b)[ir(b)],bt=new Set(Array.isArray(Je)?Je:[]);bt.has(He)?bt.delete(He):bt.add(He),vo(b,Array.from(bt)),_n(b);return}if(qe){vo(b,He),_n(b),Nr(b);return}if(Pe){let Je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Je);let bt=b.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=xl(b).length===0);return}tr(b,He,{source:"pick",values:[He]});return}if(T==="submit-multi"){let He=xl(b);if(He.length===0)return;tr(b,He.join(", "),{source:"multi",values:He});return}if(T==="open-free-text"){let He=b.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Pe=He.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(T==="focus-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(T==="submit-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(ae=He==null?void 0:He.value)!=null?ae:"";if(!Pe.trim())return;if(bo(b)){vo(b,Pe.trim()),_n(b),Nr(b);return}tr(b,Pe,{source:"free-text"});return}if(T==="next"||T==="back"){if(!At.current)return;let He=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Pe=At.current.getMessages().find(Ne=>{var Be;return((Be=Ne.toolCall)==null?void 0:Be.id)===He});if(!Pe)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Je=(Fe=(ve=qe==null?void 0:qe.value)==null?void 0:ve.trim())!=null?Fe:"";if(Je){let Ne=Vo(b)[ir(b)];(typeof Ne!="string"||Ne!==Je)&&vo(b,Je)}let bt=T==="next"?1:-1,P=ir(b)+bt;Va(b,Pe,r,P),_n(b);return}if(T==="submit-all"){if(!At.current)return;let He=(Se=b.getAttribute("data-tool-call-id"))!=null?Se:"",Pe=At.current.getMessages().find(Ne=>{var Be;return((Be=Ne.toolCall)==null?void 0:Be.id)===He});if(!Pe)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Je=(je=(st=qe==null?void 0:qe.value)==null?void 0:st.trim())!=null?je:"";Je&&vo(b,Je);let bt=za(b,Pe);At.current.persistAskUserQuestionProgress(Pe,{answers:bt,currentIndex:ir(b)});let P=so(bt);tr(b,P||"(submitted)",{source:"submit-all",structured:bt});return}if(T==="skip"){if(!At.current)return;let He=(gt=b.getAttribute("data-tool-call-id"))!=null?gt:"",Pe=At.current.getMessages().find(Be=>{var fe;return((fe=Be.toolCall)==null?void 0:fe.id)===He});if(!Pe)return;let qe=bo(b),Je=ir(b),bt=ws(b),P=Je>=bt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),xo(er,He),(it=Pe.agentMetadata)!=null&&it.awaitingLocalTool&&(At.current.markAskUserQuestionResolved(Pe),At.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}vo(b,"");let Ne=b.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),P){let Be=za(b,Pe),fe=so(Be);tr(b,fe||"(skipped)",{source:"submit-all",structured:Be});return}Va(b,Pe,r,Je+1),_n(b);return}}),er.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let T=h.value;if(T.trim()){if(bo(b)){vo(b,T.trim()),_n(b),Nr(b);return}tr(b,T,{source:"free-text"})}});let ao=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if((u==null?void 0:u.tagName)==="INPUT"||(u==null?void 0:u.tagName)==="TEXTAREA"||u!=null&&u.isContentEditable)return;let h=er.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",ao);let $n=null,Bt=null,Tn=null,nr=null,io=()=>{};function Or(){nr==null||nr(),nr=null}let lo=()=>{var z;if(!$n||!Bt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let b=$n.firstElementChild;if(!b||b===Bt)return;let T=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${T}px`,Bt.style.zIndex="5";let W=b.offsetWidth-T/2;Bt.style.left=`${Math.max(0,W)}px`},Sr=()=>{},jn=()=>{var h,b,T,W,z;if(!Ct||!cr(r))return;Di(e,r),Ni(e,r),Sr();let l=(W=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?W:520,u=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ct.update(Fn),An?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(z=Ct.backdrop)==null||z.classList.add("persona-hidden")):Fn.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),io()};if(cr(r)){de.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(pe),Ct=Fg(r,{onSelect:h=>{var b;return(b=At.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{An=!0,jn()}}),Ct.element.classList.add("persona-hidden"),$n=u,u.appendChild(l),u.appendChild(Ct.element),Ct.backdrop&&de.appendChild(Ct.backdrop),de.appendChild(u),io=()=>{var b,T,W,z;if(!$n||!Ct)return;if(!(((W=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:W.resizable)===!0)){Tn==null||Tn(),Tn=null,Or(),Bt&&(Bt.remove(),Bt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Bt){let F=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");F.setAttribute("role","separator"),F.setAttribute("aria-orientation","vertical"),F.setAttribute("aria-label","Resize artifacts panel"),F.tabIndex=0;let B=e.ownerDocument,se=(z=B.defaultView)!=null?z:window,ae=Z=>{var gt,it;if(!Ct||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Or();let ve=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Se=(it=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:it.layout,st=He=>{let Pe=$n.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Je=qe?0:Ug($n,se),bt=qe?0:F.getBoundingClientRect().width||6,P=Fe-(He.clientX-ve),Ne=qg(P,Pe,Je,bt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ct.element.style.width=`${Ne}px`,Ct.element.style.maxWidth="none",lo()},je=()=>{B.removeEventListener("pointermove",st),B.removeEventListener("pointerup",je),B.removeEventListener("pointercancel",je),nr=null;try{F.releasePointerCapture(Z.pointerId)}catch{}};nr=je,B.addEventListener("pointermove",st),B.addEventListener("pointerup",je),B.addEventListener("pointercancel",je);try{F.setPointerCapture(Z.pointerId)}catch{}};F.addEventListener("pointerdown",ae),Bt=F,$n.insertBefore(F,Ct.element),Tn=()=>{F.removeEventListener("pointerdown",ae)}}if(Bt){let F=Fn.artifacts.length>0&&!An;Bt.classList.toggle("persona-hidden",!F),lo()}},Sr=()=>{var se,ae,Z,ve,Fe,Se,st,je,gt,it,He,Pe,qe,Je;if(!S||!Ct||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||on(r)&&Xn(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,T=(Fe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Fe:!0,W=(st=(Se=r.launcher)==null?void 0:Se.mobileBreakpoint)!=null?st:640;if(T&&b.innerWidth<=W||!jg(r,S))return;let z=(it=(gt=(je=r.launcher)==null?void 0:je.width)!=null?gt:r.launcherWidth)!=null?it:Qn,F=(Je=(qe=(Pe=(He=r.features)==null?void 0:He.artifacts)==null?void 0:Pe.layout)==null?void 0:qe.expandedPanelWidth)!=null?Je:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!An?(de.style.width=F,de.style.maxWidth=F):(de.style.width=z,de.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{jn()}),On.observe(de))}else de.appendChild(pe),D()&&tt&&(Y.peekBanner&&tt.appendChild(Y.peekBanner),tt.appendChild(Re));e.appendChild(Oe),tt&&e.appendChild(tt);let be=()=>{var Ne,Be,fe,Ot,Dt,zt,wt,jt,Kn,Yt,Xe,kt,rn,ar,Gn,No,Oo,gs,fs,Vt,Fo,go,fo,zr,_o,gr,et,cn;if(D()){de.style.width="100%",de.style.maxWidth="100%";let _t=(Be=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?Be:{},Ft=Oe.dataset.state==="expanded",ft=(fe=_t.expandedSize)!=null?fe:"anchored";if(!(Ft&&ft!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let St=(Dt=(Ot=r.theme)==null?void 0:Ot.components)==null?void 0:Dt.panel,xn=Ps(r),En=(kn,$o)=>{var Gs;return kn==null||kn===""?$o:(Gs=ks(xn,kn))!=null?Gs:kn},Ir="1px solid var(--persona-border)",un="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=En(St==null?void 0:St.border,Ir),pe.style.borderRadius=En(St==null?void 0:St.borderRadius,Mn),pe.style.boxShadow=En(St==null?void 0:St.shadow,un),pe.style.overflow="hidden";return}let l=on(r),u=(wt=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?wt:!1,h=l||u||((Kn=(jt=r.launcher)==null?void 0:jt.fullHeight)!=null?Kn:!1),b=((Yt=r.launcher)==null?void 0:Yt.enabled)===!1,T=(kt=(Xe=r.theme)==null?void 0:Xe.components)==null?void 0:kt.panel,W=Ps(r),z=(_t,Ft)=>{var ft;return _t==null||_t===""?Ft:(ft=ks(W,_t))!=null?ft:_t},F=(rn=e.ownerDocument.defaultView)!=null?rn:window,B=(Gn=(ar=r.launcher)==null?void 0:ar.mobileFullscreen)!=null?Gn:!0,se=(Oo=(No=r.launcher)==null?void 0:No.mobileBreakpoint)!=null?Oo:640,ae=F.innerWidth<=se,Z=B&&ae&&S,ve=(fs=(gs=r.launcher)==null?void 0:gs.position)!=null?fs:"bottom-left",Fe=ve==="bottom-left"||ve==="top-left",Se=(Fo=(Vt=r.launcher)==null?void 0:Vt.zIndex)!=null?Fo:Cn,st=u||Z?"none":"1px solid var(--persona-border)",je=Z?"none":u?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(je="none",st="none");let gt=u||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=z(T==null?void 0:T.border,st),He=z(T==null?void 0:T.shadow,je),Pe=z(T==null?void 0:T.borderRadius,gt),qe=Ce.scrollTop;e.style.cssText="",Oe.style.cssText="",de.style.cssText="",pe.style.cssText="",Ce.style.cssText="",Re.style.cssText="";let Je=()=>{var Ft;if(qe<=0)return;((Ft=Ce.ownerDocument.defaultView)!=null?Ft:window).requestAnimationFrame(()=>{if(Ce.scrollTop===qe)return;let ft=Ce.scrollHeight-Ce.clientHeight;ft<=0||(Ce.scrollTop=Math.min(qe,ft))})};if(Z){Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Oe.style.cssText=`
|
|
34
|
+
`,H.addEventListener("click",()=>{m=A,S.forEach((D,N)=>{let L=N<A;D.classList.toggle("selected",L),D.setAttribute("aria-checked",N===A-1?"true":"false")})}),S.push(H),M.appendChild(H)}f.appendChild(M);let R=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),A.appendChild(R),f.appendChild(A)}let O=document.createElement("div");O.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(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=(R==null?void 0:R.value.trim())||void 0;await t(m,A),p.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),O.appendChild(k),O.appendChild(I),f.appendChild(O),p.appendChild(f),p}function qi(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,x.appendChild(M),g.appendChild(x);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,R.appendChild(O),R.appendChild(k);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let U=0;U<=10;U++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${U} out of 10`),V.textContent=String(U),V.dataset.rating=String(U),U<=6?V.classList.add("persona-feedback-detractor"):U<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=U,A.forEach((ne,Ie)=>{ne.classList.toggle("selected",Ie===U),ne.setAttribute("aria-checked",Ie===U?"true":"false")})}),A.push(V),I.appendChild(V)}S.appendChild(R),S.appendChild(I),g.appendChild(S);let H=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=o,H.rows=3,H.setAttribute("aria-label","Additional comments"),U.appendChild(H),g.appendChild(U)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{n==null||n(),m.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let U=(H==null?void 0:H.value.trim())||void 0;await t(f,U),m.remove()}catch(U){L.disabled=!1,L.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),D.appendChild(N),D.appendChild(L),g.appendChild(D),m.appendChild(g),m}var Os="persona-chat-history",$b=30*1e3,jb={"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 Ub(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=jb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function zi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function qb(e){var t,n,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function zb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var oc=e=>!e||typeof e!="object"?{}:{...e},tf=e=>e.map(t=>({...t,streaming:!1})),nf=(e,t,n)=>{let r=e!=null&&e.markdown?zo(e.markdown):null,s=bs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var p,m,f;let a=(p=o.text)!=null?p:"",i=(m=o.message.rawContent)!=null?m:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d=qo()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...o,text:a,raw:(f=i!=null?i:o.text)!=null?f:""});c=s?s(g):g}else if(r){let g=o.streaming?lm(a):a,x=r(g);c=s&&d?s(x):x}else c=Rr(a);return c}};function rf(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=xe(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=y("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Vi=(e,t,n)=>{var Jc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Sd,Ad,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd;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=pi(t),s=Ea.getForInstance(r.plugins);r.components&&Zr.registerAll(r.components);let o=Qg(),i=r.persistState===!1?null:(Jc=r.storageAdapter)!=null?Jc:Oi(),d={},c=null,p=!1,m=l=>{if(r.onStateLoaded)try{let u=r.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:b}=u;return b&&(p=!0),h}return u}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return m(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=m(u);h.metadata&&(d=oc(h.metadata)),(Qc=h.messages)!=null&&Qc.length&&(r={...r,initialMessages:h.messages}),(Xc=h.artifacts)!=null&&Xc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Yc=h.selectedArtifactId)!=null?Yc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(Zc=l.messages)!=null&&Zc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let f=()=>d,g=l=>{var h;d=(h=l({...d}))!=null?h:{},co()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ma],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],M=ka({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let S=(td=(ed=r.launcher)==null?void 0:ed.enabled)!=null?td:!0,R=(rd=(nd=r.launcher)==null?void 0:nd.autoExpand)!=null?rd:!1,O=(od=r.autoFocusInput)!=null?od:!1,k=R,I=S,A=(ad=(sd=r.layout)==null?void 0:sd.header)==null?void 0:ad.layout,H=!1,D=()=>Eo(r),N=()=>S||D(),L=D()?!1:S?R:!0,U=!1,V=null,ne=()=>{U=!0,V&&clearTimeout(V),V=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Ie=nf(r,M,ne),Ue=(ld=(id=r.features)==null?void 0:id.showReasoning)!=null?ld:!0,Ae=(dd=(cd=r.features)==null?void 0:cd.showToolCalls)!=null?dd:!0,Le=(ud=(pd=r.features)==null?void 0:pd.showEventStreamToggle)!=null?ud:!1,_e=(gd=(md=r.features)==null?void 0:md.scrollToBottom)!=null?gd:{},ye=(hd=(fd=r.features)==null?void 0:fd.scrollBehavior)!=null?hd:{},ie=`${(bd=typeof r.persistState=="object"?(yd=r.persistState)==null?void 0:yd.keyPrefix:void 0)!=null?bd:"persona-"}event-stream`,X=Le?new Aa(ie):null,re=(wd=(vd=(xd=r.features)==null?void 0:xd.eventStream)==null?void 0:vd.maxEvents)!=null?wd:2e3,ce=Le?new Sa(re,X):null,oe=Le?new Ta:null,J=null,te=!1,ze=null,Q=0;X==null||X.open().then(()=>ce==null?void 0:ce.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let le={onCopy:l=>{var u,h;o.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;o.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},We=(Cd=r.statusIndicator)!=null?Cd:{},we=l=>{var u,h,b,T;return l==="idle"?(u=We.idleText)!=null?u:wn.idle:l==="connecting"?(h=We.connectingText)!=null?h:wn.connecting:l==="connected"?(b=We.connectedText)!=null?b:wn.connected:l==="error"?(T=We.errorText)!=null?T:wn.error:wn[l]};function Ye(l,u,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=u,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=u}let Ge=Eg({config:r,showClose:N()}),{wrapper:Oe,panel:de,pillRoot:tt}=Ge.shell,Y=Ge.panelElements,{container:pe,body:Ce,messagesWrapper:Ve,suggestions:Pt,textarea:Te,sendButton:ge,sendButtonWrapper:hn,composerForm:It,statusText:sn,introTitle:xr,introSubtitle:yn,closeButton:Ke,iconHolder:E,headerTitle:me,headerSubtitle:ke,header:Ee,footer:Re,actionsRow:nt,leftActions:Qe,rightActions:ut}=Y,Rt=Y.setSendButtonMode,q=Y.micButton,at=Y.micButtonWrapper,K=Y.attachmentButton,ue=Y.attachmentButtonWrapper,Me=Y.attachmentInput,xt=Y.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Ce.classList.add("persona-relative");let Zt=12,en=()=>{var l;return(l=_e.label)!=null?l:""},mn=()=>{var l;return(l=_e.iconName)!=null?l:"arrow-down"},Ht=()=>_e.enabled!==!1,rt=()=>{var l;return(l=ye.mode)!=null?l:"follow"},Wt=()=>{var l;return(l=ye.anchorTopOffset)!=null?l:16},ct=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");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let Gt=y("span","persona-flex persona-items-center"),Zn=y("span",""),Sn=y("span","");Sn.setAttribute("data-persona-scroll-to-bottom-count",""),Sn.style.display="none",ct.append(Gt,Zn,Sn),pe.appendChild(ct);let tn=y("div","persona-stream-anchor-spacer");tn.setAttribute("aria-hidden","true"),tn.setAttribute("data-persona-anchor-spacer",""),tn.style.flexShrink="0",tn.style.pointerEvents="none",tn.style.height="0px",Ce.appendChild(tn);let In=()=>{let u=Re.style.display==="none"?0:Re.offsetHeight;ct.style.bottom=`${u+Zt}px`};In();let vr=()=>{let l=!!en();ct.setAttribute("aria-label",en()||"Jump to latest"),ct.title=en(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Gt.innerHTML="";let u=xe(mn(),"14px","currentColor",2);u?(Gt.appendChild(u),Gt.style.display=""):Gt.style.display="none",Zn.textContent=en(),Zn.style.display=l?"":"none"};vr();let vt=null,Nn=null,wr=s.find(l=>l.renderHeader);if(wr!=null&&wr.renderHeader){let l=wr.renderHeader({config:r,defaultRenderer:()=>{let u=Yr({config:r,showClose:N()});return Zo(pe,u,r),u.header},onClose:()=>$t(!1,"user")});if(l){let u=pe.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Ee=l,Ge.header.element=l)}}let Br=()=>{var u,h,b,T;if(!ce)return;if(te=!0,!J&&ce&&(J=_g({buffer:ce,getFullHistory:()=>ce.getAllFromStore(),onClose:()=>dr(),config:r,plugins:s,getThroughput:()=>{var W;return(W=oe==null?void 0:oe.getMetric())!=null?W:{status:"idle"}}})),J&&(Ce.style.display="none",(u=Re.parentNode)==null||u.insertBefore(J.element,Re),J.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let W=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;W&&W.split(/\s+/).forEach(z=>z&&yt.classList.add(z))}let l=()=>{if(!te)return;let W=Date.now();W-Q>=200&&(J==null||J.update(),Q=W),ze=requestAnimationFrame(l)};Q=0,ze=requestAnimationFrame(l),Ze(),o.emit("eventStream:opened",{timestamp:Date.now()})},dr=()=>{var l,u,h;if(te){if(te=!1,J&&J.element.remove(),Ce.style.display="",yt){yt.style.boxShadow="";let b=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&yt.classList.remove(T))}ze!==null&&(cancelAnimationFrame(ze),ze=null),Ze(),o.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(Le){let l=(Ad=(Sd=r.features)==null?void 0:Sd.eventStream)==null?void 0:Ad.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=y("button",u),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=xe("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let b=Y.clearChatButtonWrapper,T=Y.closeButtonWrapper,W=b||T;W&&W.parentNode===Ee?Ee.insertBefore(yt,W):Ee.appendChild(yt),yt.addEventListener("click",()=>{te?dr():Br()})}let Lo=l=>{var T,W,z,F,B;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let se=y("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=u.allowedTypes)!=null?z:Qr).join(","),se.multiple=((F=u.maxFiles)!=null?F:4)>1,se.style.display="none",se.setAttribute("aria-label",(B=u.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(se)}},Cr=s.find(l=>l.renderComposer);if(Cr!=null&&Cr.renderComposer){let l=r.composer,u=Cr.renderComposer({config:r,defaultRenderer:()=>Rs({config:r}).footer,onSubmit:h=>{var z;if(!_||_.isStreaming())return;let b=h.trim(),T=(z=vt==null?void 0:vt.hasAttachments())!=null?z:!1;if(!b&&!T)return;Ec();let W;T&&(W=[],W.push(...vt.getContentParts()),b&&W.push(la(b))),_.sendMessage(b,{contentParts:W}),T&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Me==null||Me.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Td=r.voiceRecognition)==null?void 0:Td.enabled)===!0?()=>{Nn==null||Nn()}:void 0});u&&(Ge.replaceComposer(u),Re=Ge.composer.footer)}let Po=l=>{let u=(...ae)=>{for(let Z of ae){let ve=l.querySelector(Z);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");h&&(It=h),b&&(Te=b),T&&(ge=T),W&&(q=W,at=W.parentElement),z&&(sn=z);let F=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Pt=F);let B=u("[data-persona-composer-attachment-button]",".persona-attachment-button");B&&(K=B,ue=B.parentElement),Me=u("[data-persona-composer-attachment-input]",'input[type="file"]'),xt=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(nt=se)};Lo(Re),Po(Re);let Rn=(Pd=(Ed=r.layout)==null?void 0:Ed.contentMaxWidth)!=null?Pd:D()?(Ld=(kd=(Md=r.launcher)==null?void 0:Md.composerBar)==null?void 0:kd.contentMaxWidth)!=null?Ld:"720px":void 0;if(Rn&&(Ve.style.maxWidth=Rn,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),Rn&&It&&!D()&&(It.style.maxWidth=Rn,It.style.marginLeft="auto",It.style.marginRight="auto"),Rn&&Pt&&!D()&&(Pt.style.maxWidth=Rn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Rn&&xt&&!D()&&(xt.style.maxWidth=Rn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),(Id=r.attachments)!=null&&Id.enabled&&Me&&xt){vt=Xo.fromConfig(r.attachments),vt.setPreviewsContainer(xt),Me.addEventListener("change",h=>{let b=h.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,u=rf(l);pe.appendChild(u)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},u=W=>{switch(W){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Pt;case"composer":return It;case"footer-bottom":return sn;default:return null}},h=(W,z)=>{var F;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ee.insertBefore(z,Ee.firstChild);else if(W==="header-right")Ee.appendChild(z);else{let B=Ee.querySelector(".persona-flex-col");B?(F=B.parentNode)==null||F.insertBefore(z,B.nextSibling):Ee.appendChild(z)}break;case"body-top":{let B=Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(z):Ce.insertBefore(z,Ce.firstChild);break}case"body-bottom":Ce.appendChild(z);break;case"footer-top":Pt.replaceWith(z);break;case"footer-bottom":sn.replaceWith(z);break;default:break}};for(let[W,z]of Object.entries(l))if(z)try{let F=z({config:r,defaultContent:()=>u(W)});F&&h(W,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,F)}})();let to=l=>{var z,F;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Hs.has(T)?Hs.delete(T):Hs.add(T),Pg(T,b);else if(W==="tool")Bs.has(T)?Bs.delete(T):Bs.add(T),Ig(T,b,r);else if(W==="approval"){let B=r.approval!==!1?r.approval:void 0,se=((z=B==null?void 0:B.detailsDisplay)!=null?z:"collapsed")==="expanded",ae=(F=Wi.get(T))!=null?F:se;Wi.set(T,!ae),Bg(T,b,r)}Mr.delete(T)};Ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),to(l))}),Ve.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),to(l))}),Ve.addEventListener("copy",l=>{let{clipboardData:u}=l;if(!u)return;let h=Ve.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let T=b.toString(),W=ag(T);!W||W===T||(u.setData("text/plain",W),l.preventDefault())});let Dr=new Map,no=null,ro="idle",Io={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ro=(l,u)=>{let{icon:h,label:b}=Io[u];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let T=xe(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},oo=()=>{Ve.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{var W;let h=u.closest("[data-actions-for]"),b=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ro(u,b&&b===no?ro:"idle")})};Ve.addEventListener("click",l=>{var z;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let W=h.getAttribute("data-action");if(W==="copy"){let B=_.getMessages().find(se=>se.id===T);if(B&&le.onCopy){let se=B.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=xe("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=xe("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),le.onCopy(B)}}else if(W==="read-aloud")_.toggleReadAloud(T);else if(W==="upvote"||W==="downvote"){let B=((z=Dr.get(T))!=null?z:null)===W,se=W==="upvote"?"thumbs-up":"thumbs-down";if(B){Dr.delete(T),h.classList.remove("persona-message-action-active");let ae=xe(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=W==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ae}"]`);if(Z){Z.classList.remove("persona-message-action-active");let je=xe(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(Z.innerHTML="",Z.appendChild(je))}Dr.set(T,W),h.classList.add("persona-message-action-active");let ve=xe(se,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(st=>st.id===T);Se&&le.onFeedback&&le.onFeedback({type:W,messageId:Se.id,message:Se})}}}),Ve.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",B=_.getMessages().find(ae=>ae.id===T);if(!(B!=null&&B.approval))return;let se=b.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(T,z):_.resolveApproval(B.approval,z)});let Ct=null,On=null,Fn={artifacts:[],selectedId:null},An=!1,At={current:null};Ve.addEventListener("click",l=>{var Z,ve,Fe,Se,st;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(ve=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Fe.call(ve,{type:"download",artifactId:b}))===!0)return;let W=_.getArtifactById(b),z=W==null?void 0:W.markdown,F=(W==null?void 0:W.title)||"artifact";if(!z){let je=h.closest("[data-open-artifact]"),gt=je==null?void 0:je.closest("[data-message-id]"),it=gt==null?void 0:gt.getAttribute("data-message-id");if(it){let Pe=_.getMessages().find(qe=>qe.id===it);if(Pe!=null&&Pe.rawContent)try{let qe=JSON.parse(Pe.rawContent);z=(Se=qe==null?void 0:qe.props)==null?void 0:Se.markdown,F=((st=qe==null?void 0:qe.props)==null?void 0:st.title)||F}catch{}}}if(!z)return;let B=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(B),ae=document.createElement("a");ae.href=se,ae.download=`${F}.md`,ae.click(),URL.revokeObjectURL(se)}),Ve.addEventListener("click",l=>{var W,z,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((F=(z=(W=r.features)==null?void 0:W.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:F.call(z,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),An=!1,_.selectArtifact(b),jn())}),Ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let er=Y.composerOverlay,tr=(l,u,h)=>{var F,B,se,ae;let b=u.trim();if(!b||!At.current)return;let T=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(B=h.values)!=null?B:h.source==="multi"?b.split(", "):[b],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),xo(er,T);let z=At.current.getMessages().find(Z=>{var ve;return((ve=Z.toolCall)==null?void 0:ve.id)===T});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?At.current.resolveAskUserQuestion(z,(ae=h.structured)!=null?ae:b):At.current.sendMessage(b)},_n=l=>{var T;let u=At.current;if(!u)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=u.getMessages().find(W=>{var z;return((z=W.toolCall)==null?void 0:z.id)===h});b&&u.persistAskUserQuestionProgress(b,{answers:za(l,b),currentIndex:ir(l)})},so=l=>Object.entries(l).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Nr=l=>{var T,W,z;if(((W=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let u=ir(l),h=ws(l);if(u>=h-1)return;let b=(z=At.current)==null?void 0:z.getMessages().find(F=>{var B;return((B=F.toolCall)==null?void 0:B.id)===l.getAttribute("data-tool-call-id")});b&&(Va(l,b,r,u+1),_n(l))};er.addEventListener("click",l=>{var W,z,F,B,se,ae,Z,ve,Fe,Se,st,je,gt,it;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let He=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),xo(er,He);let Pe=(z=At.current)==null?void 0:z.getMessages().find(qe=>{var Je;return((Je=qe.toolCall)==null?void 0:Je.id)===He});(F=Pe==null?void 0:Pe.agentMetadata)!=null&&F.awaitingLocalTool&&((B=At.current)==null||B.markAskUserQuestionResolved(Pe),(se=At.current)==null||se.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(T==="pick"){let He=h.getAttribute("data-option-label");if(!He)return;let Pe=b.getAttribute("data-multi-select")==="true",qe=bo(b);if(qe&&Pe){let Je=Vo(b)[ir(b)],bt=new Set(Array.isArray(Je)?Je:[]);bt.has(He)?bt.delete(He):bt.add(He),vo(b,Array.from(bt)),_n(b);return}if(qe){vo(b,He),_n(b),Nr(b);return}if(Pe){let Je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Je);let bt=b.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=xl(b).length===0);return}tr(b,He,{source:"pick",values:[He]});return}if(T==="submit-multi"){let He=xl(b);if(He.length===0)return;tr(b,He.join(", "),{source:"multi",values:He});return}if(T==="open-free-text"){let He=b.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Pe=He.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(T==="focus-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(T==="submit-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(ae=He==null?void 0:He.value)!=null?ae:"";if(!Pe.trim())return;if(bo(b)){vo(b,Pe.trim()),_n(b),Nr(b);return}tr(b,Pe,{source:"free-text"});return}if(T==="next"||T==="back"){if(!At.current)return;let He=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Pe=At.current.getMessages().find(Ne=>{var Be;return((Be=Ne.toolCall)==null?void 0:Be.id)===He});if(!Pe)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Je=(Fe=(ve=qe==null?void 0:qe.value)==null?void 0:ve.trim())!=null?Fe:"";if(Je){let Ne=Vo(b)[ir(b)];(typeof Ne!="string"||Ne!==Je)&&vo(b,Je)}let bt=T==="next"?1:-1,P=ir(b)+bt;Va(b,Pe,r,P),_n(b);return}if(T==="submit-all"){if(!At.current)return;let He=(Se=b.getAttribute("data-tool-call-id"))!=null?Se:"",Pe=At.current.getMessages().find(Ne=>{var Be;return((Be=Ne.toolCall)==null?void 0:Be.id)===He});if(!Pe)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Je=(je=(st=qe==null?void 0:qe.value)==null?void 0:st.trim())!=null?je:"";Je&&vo(b,Je);let bt=za(b,Pe);At.current.persistAskUserQuestionProgress(Pe,{answers:bt,currentIndex:ir(b)});let P=so(bt);tr(b,P||"(submitted)",{source:"submit-all",structured:bt});return}if(T==="skip"){if(!At.current)return;let He=(gt=b.getAttribute("data-tool-call-id"))!=null?gt:"",Pe=At.current.getMessages().find(Be=>{var fe;return((fe=Be.toolCall)==null?void 0:fe.id)===He});if(!Pe)return;let qe=bo(b),Je=ir(b),bt=ws(b),P=Je>=bt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),xo(er,He),(it=Pe.agentMetadata)!=null&&it.awaitingLocalTool&&(At.current.markAskUserQuestionResolved(Pe),At.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}vo(b,"");let Ne=b.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),P){let Be=za(b,Pe),fe=so(Be);tr(b,fe||"(skipped)",{source:"submit-all",structured:Be});return}Va(b,Pe,r,Je+1),_n(b);return}}),er.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let T=h.value;if(T.trim()){if(bo(b)){vo(b,T.trim()),_n(b),Nr(b);return}tr(b,T,{source:"free-text"})}});let ao=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if((u==null?void 0:u.tagName)==="INPUT"||(u==null?void 0:u.tagName)==="TEXTAREA"||u!=null&&u.isContentEditable)return;let h=er.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",ao);let $n=null,Bt=null,Tn=null,nr=null,io=()=>{};function Or(){nr==null||nr(),nr=null}let lo=()=>{var z;if(!$n||!Bt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let b=$n.firstElementChild;if(!b||b===Bt)return;let T=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${T}px`,Bt.style.zIndex="5";let W=b.offsetWidth-T/2;Bt.style.left=`${Math.max(0,W)}px`},Sr=()=>{},jn=()=>{var h,b,T,W,z;if(!Ct||!cr(r))return;Di(e,r),Ni(e,r),Sr();let l=(W=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?W:520,u=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ct.update(Fn),An?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(z=Ct.backdrop)==null||z.classList.add("persona-hidden")):Fn.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),io()};if(cr(r)){de.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(pe),Ct=Ug(r,{onSelect:h=>{var b;return(b=At.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{An=!0,jn()}}),Ct.element.classList.add("persona-hidden"),$n=u,u.appendChild(l),u.appendChild(Ct.element),Ct.backdrop&&de.appendChild(Ct.backdrop),de.appendChild(u),io=()=>{var b,T,W,z;if(!$n||!Ct)return;if(!(((W=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:W.resizable)===!0)){Tn==null||Tn(),Tn=null,Or(),Bt&&(Bt.remove(),Bt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Bt){let F=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");F.setAttribute("role","separator"),F.setAttribute("aria-orientation","vertical"),F.setAttribute("aria-label","Resize artifacts panel"),F.tabIndex=0;let B=e.ownerDocument,se=(z=B.defaultView)!=null?z:window,ae=Z=>{var gt,it;if(!Ct||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Or();let ve=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Se=(it=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:it.layout,st=He=>{let Pe=$n.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Je=qe?0:Kg($n,se),bt=qe?0:F.getBoundingClientRect().width||6,P=Fe-(He.clientX-ve),Ne=Gg(P,Pe,Je,bt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ct.element.style.width=`${Ne}px`,Ct.element.style.maxWidth="none",lo()},je=()=>{B.removeEventListener("pointermove",st),B.removeEventListener("pointerup",je),B.removeEventListener("pointercancel",je),nr=null;try{F.releasePointerCapture(Z.pointerId)}catch{}};nr=je,B.addEventListener("pointermove",st),B.addEventListener("pointerup",je),B.addEventListener("pointercancel",je);try{F.setPointerCapture(Z.pointerId)}catch{}};F.addEventListener("pointerdown",ae),Bt=F,$n.insertBefore(F,Ct.element),Tn=()=>{F.removeEventListener("pointerdown",ae)}}if(Bt){let F=Fn.artifacts.length>0&&!An;Bt.classList.toggle("persona-hidden",!F),lo()}},Sr=()=>{var se,ae,Z,ve,Fe,Se,st,je,gt,it,He,Pe,qe,Je;if(!S||!Ct||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||on(r)&&Xn(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,T=(Fe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Fe:!0,W=(st=(Se=r.launcher)==null?void 0:Se.mobileBreakpoint)!=null?st:640;if(T&&b.innerWidth<=W||!Vg(r,S))return;let z=(it=(gt=(je=r.launcher)==null?void 0:je.width)!=null?gt:r.launcherWidth)!=null?it:Qn,F=(Je=(qe=(Pe=(He=r.features)==null?void 0:He.artifacts)==null?void 0:Pe.layout)==null?void 0:qe.expandedPanelWidth)!=null?Je:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!An?(de.style.width=F,de.style.maxWidth=F):(de.style.width=z,de.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{jn()}),On.observe(de))}else de.appendChild(pe),D()&&tt&&(Y.peekBanner&&tt.appendChild(Y.peekBanner),tt.appendChild(Re));e.appendChild(Oe),tt&&e.appendChild(tt);let be=()=>{var Ne,Be,fe,Ot,Dt,zt,wt,jt,Kn,Yt,Xe,kt,rn,ar,Gn,No,Oo,gs,fs,Vt,Fo,go,fo,zr,_o,gr,et,cn;if(D()){de.style.width="100%",de.style.maxWidth="100%";let _t=(Be=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?Be:{},Ft=Oe.dataset.state==="expanded",ft=(fe=_t.expandedSize)!=null?fe:"anchored";if(!(Ft&&ft!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let St=(Dt=(Ot=r.theme)==null?void 0:Ot.components)==null?void 0:Dt.panel,xn=Ps(r),En=(kn,$o)=>{var Gs;return kn==null||kn===""?$o:(Gs=ks(xn,kn))!=null?Gs:kn},Ir="1px solid var(--persona-border)",un="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=En(St==null?void 0:St.border,Ir),pe.style.borderRadius=En(St==null?void 0:St.borderRadius,Mn),pe.style.boxShadow=En(St==null?void 0:St.shadow,un),pe.style.overflow="hidden";return}let l=on(r),u=(wt=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?wt:!1,h=l||u||((Kn=(jt=r.launcher)==null?void 0:jt.fullHeight)!=null?Kn:!1),b=((Yt=r.launcher)==null?void 0:Yt.enabled)===!1,T=(kt=(Xe=r.theme)==null?void 0:Xe.components)==null?void 0:kt.panel,W=Ps(r),z=(_t,Ft)=>{var ft;return _t==null||_t===""?Ft:(ft=ks(W,_t))!=null?ft:_t},F=(rn=e.ownerDocument.defaultView)!=null?rn:window,B=(Gn=(ar=r.launcher)==null?void 0:ar.mobileFullscreen)!=null?Gn:!0,se=(Oo=(No=r.launcher)==null?void 0:No.mobileBreakpoint)!=null?Oo:640,ae=F.innerWidth<=se,Z=B&&ae&&S,ve=(fs=(gs=r.launcher)==null?void 0:gs.position)!=null?fs:"bottom-left",Fe=ve==="bottom-left"||ve==="top-left",Se=(Fo=(Vt=r.launcher)==null?void 0:Vt.zIndex)!=null?Fo:Cn,st=u||Z?"none":"1px solid var(--persona-border)",je=Z?"none":u?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(je="none",st="none");let gt=u||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=z(T==null?void 0:T.border,st),He=z(T==null?void 0:T.shadow,je),Pe=z(T==null?void 0:T.borderRadius,gt),qe=Ce.scrollTop;e.style.cssText="",Oe.style.cssText="",de.style.cssText="",pe.style.cssText="",Ce.style.cssText="",Re.style.cssText="";let Je=()=>{var Ft;if(qe<=0)return;((Ft=Ce.ownerDocument.defaultView)!=null?Ft:window).requestAnimationFrame(()=>{if(Ce.scrollTop===qe)return;let ft=Ce.scrollHeight-Ce.clientHeight;ft<=0||(Ce.scrollTop=Math.min(qe,ft))})};if(Z){Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Oe.style.cssText=`
|
|
33
35
|
position: fixed !important;
|
|
34
36
|
inset: 0 !important;
|
|
35
37
|
width: 100% !important;
|
|
@@ -106,9 +108,9 @@ _Details: ${n.message}_`:r}var pa=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
106
108
|
flex-shrink: 0 !important;
|
|
107
109
|
border-top: none !important;
|
|
108
110
|
padding: 8px 16px 12px 16px !important;
|
|
109
|
-
`}if(!b&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Ft=u?"":"padding-top: 1.25em !important;",ft=u?"":`z-index: ${(cn=(et=r.launcher)==null?void 0:et.zIndex)!=null?cn:Cn} !important;`;Oe.style.cssText+=_t+Ft+ft}Je()};be(),So(e,r),Di(e,r),Ni(e,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",ao)});let Qt=null,an=null;dt.push(()=>{Qt==null||Qt(),Qt=null,an==null||an(),an=null}),On&&dt.push(()=>{On==null||On.disconnect(),On=null}),dt.push(()=>{Tn==null||Tn(),Tn=null,Or(),Bt&&(Bt.remove(),Bt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Le&&dt.push(()=>{ze!==null&&(cancelAnimationFrame(ze),ze=null),J==null||J.destroy(),J=null,ce==null||ce.destroy(),ce=null,X=null});let Ar=null,Fs=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=gi(()=>{So(e,r)}))};Fs(),dt.push(()=>{Ar&&(Ar(),Ar=null)});let Fr=(Rd=r.features)==null?void 0:Rd.streamAnimation;if(Fr!=null&&Fr.type&&Fr.type!=="none"){let l=ha(Fr.type,Fr.plugins);l&&(Nl(l,e),dt.push(()=>yg(e)))}let Wo=Rg(Pt),Tr=null,_,os=l=>{var b,T;if(!_)return;let u=l!=null?l:_.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?Ga(u):null;h?Wo.render(h,_,Te,u,r.suggestionChipsConfig,{agentPushed:!0}):u.some(W=>W.role==="user")?Wo.render([],_,Te,u):Wo.render(r.suggestionChips,_,Te,u,r.suggestionChipsConfig)},Er=!1,Mr=sg(),_r=new Map,kr=new Map,pr=new Map,ss=0,Ia=qo()!==null,Un=yi(),qn=0,ur=null,mr=!1,Ho=!1,$r=0,bn=null,Lr=null,as=!1,Bo=!1,is=null,Ra=4,ls=24,Wa=80,cs=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},_s=(Hd=(Wd=r.voiceRecognition)==null?void 0:Wd.autoResume)!=null?Hd:!1,rr=l=>{o.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},Wn=()=>{g(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},Ha=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=oc(d.voiceState),u=!!l.active,h=Number((T=l.timestamp)!=null?T:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Hb&&setTimeout(()=>{var W,z;ht.active||(ht.manuallyDeactivated=!1,((z=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:z.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),rr("restore"),_.isVoiceActive()&&us()}):Na("restore"))},1e3)},Ba=()=>_?Xg(_.getMessages()).filter(l=>!l.__skipPersist):[];function co(l){if(!(i!=null&&i.save))return;let h={messages:l?Xg(l):_?Ba():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let ot=null,w=()=>Oe.querySelector("#persona-scroll-container")||Ce,j=()=>{ot!==null&&(cancelAnimationFrame(ot),ot=null),mr=!1},$=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),Ho=!1,j()},G=()=>{$r>0?(Sn.textContent=String($r),Sn.style.display="",ct.setAttribute("aria-label",`${en()||"Jump to latest"} (${$r} new)`)):(Sn.textContent="",Sn.style.display="none",ct.setAttribute("aria-label",en()||"Jump to latest"))},he=()=>{$r!==0&&($r=0,G())},$e=()=>rt()==="follow"?!Un.isFollowing():!Yo(Ce,ls),Ze=()=>{if(!Ht()||te){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==pe&&pe.appendChild(ct),In();let u=Xr(Ce)>0&&$e();u||he(),ct.style.display=u?"":"none"},Mt=()=>{Un.pause()&&($(),Ze())},jr=()=>{Un.resume(),he(),Ze()},Hn=(l=!1)=>{rt()==="follow"&&Un.isFollowing()&&(!l&&!Er||(ur!==null&&(cancelAnimationFrame(ur),ur=null),Ho=!0,ur=requestAnimationFrame(()=>{ur=null,Ho=!1,Un.isFollowing()&&gn(w(),l?220:140)})))},zn=(l,u,h,b=()=>!0)=>{let T=l.scrollTop,W=u(),z=W-T;j();let F=performance.now();mr=!0;let B=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!b()){j();return}let Z=u();Z!==W&&(W=Z,z=W-T);let ve=ae-F,Fe=Math.min(ve/h,1),Se=B(Fe),st=T+z*Se;l.scrollTop=st,qn=l.scrollTop,Fe<1?ot=requestAnimationFrame(se):(l.scrollTop=W,qn=l.scrollTop,ot=null,mr=!1)};ot=requestAnimationFrame(se)},gn=(l,u=500)=>{let h=Xr(l)-l.scrollTop;if(Math.abs(h)<1){qn=l.scrollTop;return}if(Math.abs(h)>=Wa){j(),mr=!0,l.scrollTop=Xr(l),qn=l.scrollTop,mr=!1;return}zn(l,()=>Xr(l),u,()=>Un.isFollowing())},po=()=>{let l=w();mr=!0,l.scrollTop=Xr(l),qn=l.scrollTop,mr=!1,Ze()},Ur=l=>{tn.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},fn=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),j(),bn=null,tn.style.height="0px"},Bn=l=>{Lr!==null&&cancelAnimationFrame(Lr),Lr=requestAnimationFrame(()=>{var se;Lr=null;let u=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Ce.querySelector(`[data-message-id="${u}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Ce;)b+=T.offsetTop,T=T.offsetParent;let W=(se=bn==null?void 0:bn.spacerHeight)!=null?se:0,z=Ce.scrollHeight-W,{targetScrollTop:F,spacerHeight:B}=dg({anchorOffsetTop:b,topOffset:Wt(),viewportHeight:Ce.clientHeight,contentHeight:z});bn={initialSpacerHeight:B,contentHeightAtAnchor:z,spacerHeight:B},Ur(B),zn(Ce,()=>F,220)})},Vn=()=>{if(rt()==="follow"){if(!Un.isFollowing()||Yo(Ce,1))return;Hn(!Er);return}if(bn&&bn.initialSpacerHeight>0){let l=Ce.scrollHeight-bn.spacerHeight,u=pg({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});u!==bn.spacerHeight&&Ur(u)}Ze()},Ff=l=>{let u=rt();u==="follow"?(jr(),Hn(!0)):u==="anchor-top"&&Bn(l)},_f=l=>{let u=new Map;l.forEach(h=>{let b=cs.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(o.emit("assistant:message",h),!Bo&&rt()!=="anchor-top"&&$e()&&($r+=1,G(),Ze())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&o.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&o.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):o.emit("approval:requested",{approval:h.approval,message:h}))}),cs.clear(),u.forEach((h,b)=>{cs.set(b,h)})},$f=(l,u,h)=>{var it,He,Pe,qe,Je,bt;let b=document.createElement("div"),W=(()=>{var Ne;let P=s.find(Be=>Be.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),z=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),F=new Set,B=new Set,se=s.some(P=>P.renderAskUserQuestion),ae=[],Z=[],ve=r.enableComponentStreaming!==!1,Fe=s.some(P=>P.renderApproval)&&r.approval!==!1,Se=[];if(u.forEach(P=>{var Xe,kt,rn,ar,Gn,No,Oo,gs,fs,Vt,Fo,go,fo,zr,_o,gr;F.add(P.id);let Ne=se&&Kr(P),Be=Fe&&P.variant==="approval"&&!!P.approval,fe=!Ne&&P.role==="assistant"&&!P.variant&&ve&&$i(P);if(!Be&&pr.has(P.id)){let et=l.querySelector(`#wrapper-${P.id}`);et==null||et.removeAttribute("data-preserve-runtime"),pr.delete(P.id)}if(!fe&&kr.has(P.id)){let et=l.querySelector(`#wrapper-${P.id}`);et==null||et.removeAttribute("data-preserve-runtime"),kr.delete(P.id)}let Ot=Kr(P)?`:${(Xe=P.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(kt=P.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=og(P,ss)+Ot,zt=Ne||Be||fe?null:ag(Mr,P.id,Dt);if(zt){b.appendChild(zt.cloneNode(!0)),Kr(P)&&((rn=P.toolCall)!=null&&rn.id)&&((ar=P.agentMetadata)==null?void 0:ar.awaitingLocalTool)===!0&&!((Gn=P.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Cs(P,r,Y.composerOverlay));return}let wt=null,jt=s.find(et=>!!(P.variant==="reasoning"&&et.renderReasoning||P.variant==="tool"&&et.renderToolCall||!P.variant&&et.renderMessage)),Kn=(No=r.layout)==null?void 0:No.messages;if(Kr(P)&&((Oo=P.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){_r.delete(P.id);let et=l.querySelector(`#wrapper-${P.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(ra(P)&&((fs=(gs=r.features)==null?void 0:gs.suggestReplies)==null?void 0:fs.enabled)!==!1)return;if(Kr(P)&&((Fo=(Vt=r.features)==null?void 0:Vt.askUserQuestion)==null?void 0:Fo.enabled)!==!1){let et=s.find(cn=>typeof cn.renderAskUserQuestion=="function");if(et&&At.current){let cn=_r.get(P.id),_t=cn!==Dt,Ft=null;if(_t){let{payload:St,complete:xn}=Gr(P),En=P.id,Ir=()=>{var un;return(un=At.current)==null?void 0:un.getMessages().find(Mn=>Mn.id===En)};Ft=et.renderAskUserQuestion({message:P,payload:St,complete:xn,resolve:un=>{var kn;let Mn=Ir();Mn&&((kn=At.current)==null||kn.resolveAskUserQuestion(Mn,un))},dismiss:()=>{var Mn,kn,$o;let un=Ir();(Mn=un==null?void 0:un.agentMetadata)!=null&&Mn.awaitingLocalTool&&((kn=At.current)==null||kn.markAskUserQuestionResolved(un),($o=At.current)==null||$o.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let ft=cn!=null;if(_t&&Ft===null&&!ft){((go=P.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=P.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Cs(P,r,Y.composerOverlay));return}let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-${P.id}`,Kt.setAttribute("data-wrapper-id",P.id),Kt.setAttribute("data-ask-plugin-stub","true"),Kt.setAttribute("data-preserve-runtime","true"),b.appendChild(Kt),ae.push({messageId:P.id,fingerprint:Dt,bubble:Ft});return}else{((zr=P.agentMetadata)==null?void 0:zr.awaitingLocalTool)===!0&&!((_o=P.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Cs(P,r,Y.composerOverlay));return}}else if(Be){let et=s.find(ft=>typeof ft.renderApproval=="function"),_t=pr.get(P.id)!==Dt,Ft=null;if(_t&&(et!=null&&et.renderApproval)){let ft=P.id,Kt=(St,xn)=>{var Ir,un,Mn;let En=(Ir=At.current)==null?void 0:Ir.getMessages().find(kn=>kn.id===ft);En!=null&&En.approval&&(En.approval.toolType==="webmcp"?(un=At.current)==null||un.resolveWebMcpApproval(En.id,St):(Mn=At.current)==null||Mn.resolveApproval(En.approval,St,xn))};Ft=et.renderApproval({message:P,defaultRenderer:()=>Hi(P,r),config:r,approve:St=>Kt("approved",St),deny:St=>Kt("denied",St)})}if(_t&&Ft===null){let ft=l.querySelector(`#wrapper-${P.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),pr.delete(P.id),wt=Hi(P,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${P.id}`,ft.setAttribute("data-wrapper-id",P.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),b.appendChild(ft),Se.push({messageId:P.id,fingerprint:Dt,bubble:Ft});return}}else if(jt)if(P.variant==="reasoning"&&P.reasoning&&jt.renderReasoning){if(!Ue)return;wt=jt.renderReasoning({message:P,defaultRenderer:()=>Jl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&jt.renderToolCall){if(!Ae)return;wt=jt.renderToolCall({message:P,defaultRenderer:()=>Xl(P,r),config:r})}else jt.renderMessage&&(wt=jt.renderMessage({message:P,defaultRenderer:()=>{let et=Ws(P,h,Kn,r.messageActions,le,{loadingIndicatorRenderer:W,widgetConfig:r});return P.role!=="user"&&tc(et,P,r,_),et},config:r}));if(!wt&&fe){let et=ji(P);if(et){let cn=kr.get(P.id),_t=cn!==Dt,Ft=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(_t){let Kt=_i(et,{config:r,message:P,transform:h});if(Kt)if(Ft){let St=document.createElement("div");if(St.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(" "),St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let xn=document.createElement("div");xn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",xn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(xn)}St.appendChild(Kt),ft=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),St.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let xn=document.createElement("div");xn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",xn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(xn)}St.appendChild(Kt),ft=St}}if(ft||cn!=null){let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-${P.id}`,Kt.setAttribute("data-wrapper-id",P.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:P.id,fingerprint:Dt,bubble:ft});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ue)return;wt=Jl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;wt=Xl(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Hi(P,r)}else{let et=(gr=r.layout)==null?void 0:gr.messages;et!=null&&et.renderUserMessage&&P.role==="user"?wt=et.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):et!=null&&et.renderAssistantMessage&&P.role==="assistant"?wt=et.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Ws(P,h,et,r.messageActions,le,{loadingIndicatorRenderer:W,widgetConfig:r}),P.role!=="user"&&wt&&tc(wt,P,r,_)}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Yt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Yt.classList.add("persona-w-full"),Yt.appendChild(wt),ig(Mr,P.id,Dt,Yt),b.appendChild(Yt)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Be=Ne.getAttribute("data-persona-ask-sheet-for");Be&&!B.has(Be)&&xo(Y.composerOverlay,Be)}),(He=(it=r.features)==null?void 0:it.toolCallDisplay)!=null&&He.grouped){let P=[],Ne=[];u.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&Ae){Ne.push(Be);return}Ne.length>1&&P.push(Ne),Ne=[]}),Ne.length>1&&P.push(Ne),P.forEach((Be,fe)=>{var Xe,kt;let Ot=Be.map(rn=>Array.from(b.children).find(ar=>ar instanceof HTMLElement&&ar.getAttribute("data-wrapper-id")===rn.id)).filter(rn=>!!rn);if(Ot.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${fe}-${Be[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${fe}-${Be[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${Be.length} tools`,Kn=(kt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:kt.call(Xe,{messages:Be,toolCalls:Be.map(rn=>rn.toolCall).filter(rn=>!!rn),defaultSummary:jt,config:r});z(wt,Kn)||(wt.textContent=jt);let Yt=document.createElement("div");Yt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(wt,Yt),Dt.appendChild(zt),Ot[0].before(Dt),Ot.forEach((rn,ar)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),ar<Ot.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(rn),Yt.appendChild(Gn)})})}lg(Mr,F);let st=u.some(P=>P.role==="assistant"&&P.streaming),je=u[u.length-1],gt=(je==null?void 0:je.role)==="assistant"&&!je.streaming&&je.variant!=="approval";if(Er&&u.some(P=>P.role==="user")&&!st&&!gt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:es},Ne=s.find(fe=>fe.renderLoadingIndicator),Be=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(Be=Ne.renderLoadingIndicator(P)),Be===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(Be=r.loadingIndicator.render(P)),Be===null&&(Be=es()),Be){let fe=document.createElement("div"),Ot=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;fe.className=Ot?["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(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Be);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(fe),b.appendChild(Dt)}}if(!Er&&u.length>0){let P=u[u.length-1],Ne={config:r,lastMessage:P,messageCount:u.length},Be=s.find(Ot=>Ot.renderIdleIndicator),fe=null;if(Be!=null&&Be.renderIdleIndicator&&(fe=Be.renderIdleIndicator(Ne)),fe===null&&((Je=r.loadingIndicator)!=null&&Je.renderIdle)&&(fe=r.loadingIndicator.renderIdle(Ne)),fe){let Ot=document.createElement("div"),Dt=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Ot.className=Dt?["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(" "),Ot.setAttribute("data-idle-indicator","true"),Ot.appendChild(fe);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ot),b.appendChild(zt)}}if(fi(l,b),ae.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Be}of ae){let fe=l.querySelector(`#wrapper-${P}`);fe&&Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Ne),_r.set(P,Ne))}if(_r.size>0)for(let P of _r.keys())F.has(P)||_r.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Be}of Z){let fe=l.querySelector(`#wrapper-${P}`);fe&&Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Ne),kr.set(P,Ne))}if(kr.size>0)for(let P of kr.keys())F.has(P)||kr.delete(P);if(Se.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Be}of Se){let fe=l.querySelector(`#wrapper-${P}`);fe&&Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Ne),pr.set(P,Ne))}if(pr.size>0)for(let P of pr.keys())F.has(P)||pr.delete(P)},$s=(l,u,h)=>{$f(l,u,h),oo()},js=null,jf=()=>{var h;if(js)return;let l=b=>{let T=b.composedPath();T.includes(Oe)||tt&&T.includes(tt)||$t(!1,"user")};js=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Cc=()=>{var u;if(!js)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("pointerdown",js,!0),js=null};dt.push(()=>Cc());let Us=null,Uf=()=>{var h;if(Us)return;let l=b=>{b.key==="Escape"&&(b.isComposing||$t(!1,"user"))};Us=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Sc=()=>{var u;if(!Us)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("keydown",Us,!0),Us=null};dt.push(()=>Sc());let qs=!1,Ac=new Set,qf=()=>{var u,h,b,T;let l=(b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},ds=()=>{var gt,it,He,Pe;if(!D())return;let l=Y.peekBanner,u=Y.peekTextNode;if(!l||!u)return;if(L){l.classList.remove("persona-pill-peek--visible");return}let h=(gt=_==null?void 0:_.getMessages())!=null?gt:[],b;for(let qe=h.length-1;qe>=0;qe--){let Je=h[qe];if(Je.role==="assistant"&&Je.content){b=Je;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let T=b.content,W=!!b.streaming,z=qf(),F=vi(z),B=F.type!=="none"?ha(F.type,z==null?void 0:z.plugins):null,se=((it=B==null?void 0:B.isAnimating)==null?void 0:it.call(B,b))===!0,ae=B!==null&&(W||se);ae&&B&&!Ac.has(B.name)&&(Nl(B,e),Ac.add(B.name));let Z=ae&&(B!=null&&B.containerClass)?B.containerClass:null,ve=(He=u.dataset.personaPeekStreamClass)!=null?He:null;ve&&ve!==Z&&(u.classList.remove(ve),delete u.dataset.personaPeekStreamClass),Z&&ve!==Z&&(u.classList.add(Z),u.dataset.personaPeekStreamClass=Z),ae?(u.style.setProperty("--persona-stream-step",`${F.speed}ms`),u.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Fe=ae?wi(T,F.buffer,B,b,W):T;if(ae&&F.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let qe=document.createElement("div"),Je=ba();Je.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Je),fi(u,qe)}else{let qe=Math.max(0,Fe.length-100),Je=Fe.length>100?Fe.slice(-100):Fe,bt=Rr(Je);if(!ae||!B){let P=Fe.length>100?`\u2026${Je}`:Je;u.textContent!==P&&(u.textContent=P)}else{let P=bt;(B.wrap==="char"||B.wrap==="word")&&(P=ya(bt,B.wrap,`peek-${b.id}`,{skipTags:B.skipTags,startIndex:qe}));let Ne=document.createElement("div");if(Ne.innerHTML=P,B.useCaret&&Je.length>0){let Be=Ci(),fe=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ot=fe[fe.length-1];Ot!=null&&Ot.parentNode?Ot.parentNode.insertBefore(Be,Ot.nextSibling):Ne.appendChild(Be)}fi(u,Ne),(Pe=B.onAfterRender)==null||Pe.call(B,{container:u,bubble:l,messageId:b.id,message:b,speed:F.speed,duration:F.duration})}}let je=Er||qs;l.classList.toggle("persona-pill-peek--visible",je)};if(D()){let l=Y.peekBanner;if(l){let b=T=>{T.preventDefault(),T.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",b),dt.push(()=>{l.removeEventListener("pointerdown",b)})}let u=()=>{qs||(qs=!0,ds())},h=()=>{qs&&(qs=!1,ds())};de.addEventListener("pointerenter",u),de.addEventListener("pointerleave",h),dt.push(()=>{de.removeEventListener("pointerenter",u),de.removeEventListener("pointerleave",h)}),tt&&(tt.addEventListener("pointerenter",u),tt.addEventListener("pointerleave",h),dt.push(()=>{tt.removeEventListener("pointerenter",u),tt.removeEventListener("pointerleave",h)}))}let zf=l=>{var ve,Fe,Se,st,je,gt,it,He;let u=(Fe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Fe:{},h=(Se=u.expandedSize)!=null?Se:"anchored",b=(st=u.bottomOffset)!=null?st:"16px",T=u.collapsedMaxWidth,W=(je=u.expandedMaxWidth)!=null?je:"880px",z=(gt=u.expandedTopOffset)!=null?gt:"5vh",F=(it=u.modalMaxWidth)!=null?it:"880px",B=(He=u.modalMaxHeight)!=null?He:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="var(--persona-pill-area-height, 80px)",Z=Oe.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",tt){let Pe=tt.style;Pe.bottom=b,Pe.width=T!=null?T:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=F,Z.maxWidth=se,Z.maxHeight=B,Z.height=B;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${ae})`,Z.top=z,Z.width=W,Z.maxWidth=se}},zs=()=>{var B,se,ae,Z,ve,Fe,Se,st;if(!N())return;if(D()){let gt=(ae=((se=(B=r.launcher)==null?void 0:B.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",it=L?"expanded":"collapsed";Oe.dataset.state=it,Oe.dataset.expandedSize=gt,tt&&(tt.dataset.state=it,tt.dataset.expandedSize=gt),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),zf(L),pe.style.display=L?"flex":"none",be(),L?(jf(),Uf()):(Cc(),Sc()),ds();return}let l=on(r),u=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Fe:640,b=(st=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?st:!0,T=u.innerWidth<=h,W=b&&T&&S,z=Xn(r).reveal;L?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Xt?Xt.element.style.display="none":ln&&(ln.style.display="none")):(l?l&&(z==="overlay"||z==="push")&&!W?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Xt?Xt.element.style.display=l?"none":"":ln&&(ln.style.display=l?"none":""))},$t=(l,u="user")=>{var W,z;if(!N()||L===l)return;let h=L;L=l,zs();let b=(()=>{var Se,st,je,gt,it,He,Pe,qe,Je,bt;let F=(st=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?st:!1,B=(je=e.ownerDocument.defaultView)!=null?je:window,se=(it=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?it:!0,ae=(Pe=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?Pe:640,Z=B.innerWidth<=ae,ve=on(r)&&se&&Z,Fe=D()&&((bt=(Je=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Je.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return F||se&&Z&&S||ve||Fe})();if(L&&b){if(!Qt){let F=e.getRootNode(),B=F instanceof ShadowRoot?F.host:e.closest(".persona-host");B&&(Qt=Ol(B,(z=(W=r.launcher)==null?void 0:W.zIndex)!=null?z:Cn))}an||(an=Fl(e.ownerDocument))}else L||(Qt==null||Qt(),Qt=null,an==null||an(),an=null);L&&(Vs(),rt()==="follow"?Hn(!0):po());let T={open:L,source:u,timestamp:Date.now()};L&&!h?o.emit("widget:opened",T):!L&&h&&o.emit("widget:closed",T),o.emit("widget:state",{open:L,launcherEnabled:S,voiceActive:ht.active,streaming:_.isStreaming()})},el=l=>{Rt(l?"stop":"send"),q&&(q.disabled=l),Wo.buttons.forEach(u=>{u.disabled=l}),Re.dataset.personaComposerStreaming=l?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},tl=()=>{ht.active||Te&&Te.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>tl(),200)});let Tc=()=>{var h,b,T,W,z,F,B,se,ae,Z,ve;xr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",yn.textContent=(W=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Te.placeholder=(F=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?F:"How can I help...";let l=Ce.querySelector("[data-persona-intro-card]");if(l){let Fe=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Ce.classList.remove("persona-gap-3"),Ce.classList.add("persona-gap-6")):(Ce.classList.remove("persona-gap-6"),Ce.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!(_!=null&&_.isStreaming())&&(ge.textContent=(ve=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?ve:"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 l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{g(u=>({...u,sessionId:l}))}});let Do=null,Vf=()=>{Do==null&&(Do=setInterval(()=>{let l=Ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Do),Do=null;return}let u=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Qa(u-b))})},100))};_=new Ms(r,{onMessagesChanged(l){var b;$s(Ve,l,Ie),Vf(),os(l),Hn(!Er),_f(l);let u=[...l].reverse().find(T=>T.role==="user");l.length===0&&fn(),!as||Bo?(as=!0,is=(b=u==null?void 0:u.id)!=null?b:null):u&&u.id!==is&&(is=u.id,Ff(u.id));let h=ht.lastUserMessageId;u&&u.id!==h&&(ht.lastUserMessageId=u.id,o.emit("user:message",u)),ht.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),co(l),ds()},onStatusChanged(l){var b;let u=(b=r.statusIndicator)!=null?b:{};Ye(sn,(T=>{var W,z,F,B;return T==="idle"?(W=u.idleText)!=null?W:wn.idle:T==="connecting"?(z=u.connectingText)!=null?z:wn.connecting:T==="connected"?(F=u.connectedText)!=null?F:wn.connected:T==="error"?(B=u.errorText)!=null?B:wn.error:wn[T]})(l),u,l)},onStreamingChanged(l){Er=l,el(l),_&&$s(Ve,_.getMessages(),Ie),l||Hn(!0),ds()},onVoiceStatusChanged(l){var u,h;if(o.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":qr(),us();break;case"processing":qr(),Xf();break;case"speaking":qr(),Yf();break;default:l==="idle"&&_.isBargeInActive()?(qr(),us(),q==null||q.setAttribute("aria-label","End voice session")):(ht.active=!1,qr(),rr("system"),Wn());break}},onArtifactsState(l){Fn=l,jn(),co()}}),At.current=_;let nl=null;if(_.onReadAloudChange((l,u)=>{var T;no=l,ro=u,oo();let h=l!=null?l:nl;l&&(nl=l);let b=h&&(T=_.getMessages().find(W=>W.id===h))!=null?T:null;o.emit("message:read-aloud",{messageId:h,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(nl=null)}),as=!0,((Dd=(Bd=r.voiceRecognition)==null?void 0:Bd.provider)==null?void 0:Dd.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ce||r.onSSEEvent)&&_.setSSEEventCallback((l,u)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,u),oe==null||oe.processEvent(l,u),ce==null||ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),c&&c.then(l=>{var u,h,b;if(l){if(l.metadata&&(d=oc(l.metadata),M.syncFromMetadata()),(u=l.messages)!=null&&u.length){Bo=!0;try{_.hydrateMessages(l.messages)}finally{Bo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Ec=()=>{var u,h,b;!D()||L||!((b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||$t(!0,"auto")},Mc=l=>{var T;if(l.preventDefault(),_.isStreaming()){_.cancel(),oe==null||oe.reset(),J==null||J.update();return}let u=Te.value.trim(),h=(T=vt==null?void 0:vt.hasAttachments())!=null?T:!1;if(!u&&!h)return;Ec();let b;h&&(b=[],b.push(...vt.getContentParts()),u&&b.push(la(u))),Te.value="",Te.style.height="auto",Da(),_.sendMessage(u,{contentParts:b}),h&&vt.clearAttachments()},Kf=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},rl={...hi},ol=!1,Da=()=>{rl={...hi}},Gf=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var u;return(u=l.content)!=null?u:""}).filter(l=>l.length>0),Jf=l=>{if(!Te)return;ol=!0,Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),ol=!1;let u=Te.value.length;Te.setSelectionRange(u,u)},kc=()=>{ol||Da()},Lc=l=>{if(Te){if(Kf()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=Te.selectionStart===0&&Te.selectionEnd===0,h=rg({direction:l.key==="ArrowUp"?"up":"down",history:Gf(),currentValue:Te.value,atStart:u,state:rl});if(rl=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Jf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Da(),l.preventDefault(),ge.click()}}},Pc=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),oe==null||oe.reset(),J==null||J.update(),Da(),l.preventDefault(),l.stopImmediatePropagation())},Ic=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let u=Db(l.clipboardData);u.length!==0&&(l.preventDefault(),await vt.handleFiles(u))},or=null,Pr=!1,ps=null,mt=null,Rc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Na=(l="user")=>{var W,z,F,B,se,ae,Z;if(Pr||_.isStreaming())return;let u=Rc();if(!u)return;or=new u;let b=(z=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?z:2e3;or.continuous=!0,or.interimResults=!0,or.lang="en-US";let T=Te.value;or.onresult=ve=>{let Fe="",Se="";for(let je=0;je<ve.results.length;je++){let gt=ve.results[je],it=gt[0].transcript;gt.isFinal?Fe+=it+" ":Se=it}let st=T+Fe+Se;Te.value=st,ps&&clearTimeout(ps),(Fe||Se)&&(ps=window.setTimeout(()=>{let je=Te.value.trim();je&&or&&Pr&&(uo(),Te.value="",Te.style.height="auto",_.sendMessage(je,{viaVoice:!0}))},b))},or.onerror=ve=>{ve.error!=="no-speech"&&uo()},or.onend=()=>{if(Pr){let ve=Te.value.trim();ve&&ve!==T.trim()&&(Te.value="",Te.style.height="auto",_.sendMessage(ve,{viaVoice:!0})),uo()}};try{if(or.start(),Pr=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),rr(l),Wn(),q){let ve=(F=r.voiceRecognition)!=null?F:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(B=ve.iconName)!=null?B:"mic",iconSize:parseFloat((Z=(ae=ve.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Fe=ve.recordingBackgroundColor,Se=ve.recordingIconColor,st=ve.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let je=q.querySelector("svg");je&&je.setAttribute("stroke",Se)}st&&(q.style.borderColor=st),q.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Pr){if(Pr=!1,ps&&(clearTimeout(ps),ps=null),or){try{or.stop()}catch{}or=null}if(ht.active=!1,rr(l),Wn(),q){if(q.classList.remove("persona-voice-recording"),mt){q.style.backgroundColor=mt.backgroundColor,q.style.color=mt.color,q.style.borderColor=mt.borderColor;let u=q.querySelector("svg");u&&u.setAttribute("stroke",mt.color||"currentColor"),mt=null}q.setAttribute("aria-label","Start voice recognition")}}},Qf=(l,u)=>{var it,He,Pe,qe,Je,bt,P,Ne,Be;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((it=l==null?void 0:l.provider)==null?void 0:it.type)==="runtype",T=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(h||b||T))return null;let z=y("div","persona-send-button-wrapper"),F=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let B=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",se=(qe=u==null?void 0:u.size)!=null?qe:"40px",ae=(Je=l==null?void 0:l.iconSize)!=null?Je:se,Z=parseFloat(ae)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:u==null?void 0:u.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:u==null?void 0:u.textColor;F.style.width=ae,F.style.height=ae,F.style.minWidth=ae,F.style.minHeight=ae,F.style.fontSize="18px",F.style.lineHeight="1",Fe?F.style.color=Fe:F.style.color="var(--persona-text, #111827)";let st=xe(B,Z,Fe||"currentColor",1.5);st?F.appendChild(st):F.textContent="\u{1F3A4}",ve?F.style.backgroundColor=ve:F.style.backgroundColor="",l!=null&&l.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l!=null&&l.borderColor&&(F.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),z.appendChild(F);let je=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((Be=l==null?void 0:l.showTooltip)!=null?Be:!1)&&je){let fe=y("div","persona-send-button-tooltip");fe.textContent=je,z.appendChild(fe)}return{micButton:F,micButtonWrapper:z}},sl=()=>{var u,h,b,T,W;if(!q||mt)return;let l=(u=r.voiceRecognition)!=null?u:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},al=(l,u)=>{var W,z,F,B,se;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let b=(se=mt==null?void 0:mt.iconSize)!=null?se:parseFloat((B=(F=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?F:(z=r.sendButton)==null?void 0:z.size)!=null?B:"40")||24,T=xe(l,b,u,1.5);T&&q.appendChild(T)},Oa=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},us=()=>{var T;if(!q)return;sl();let l=(T=r.voiceRecognition)!=null?T:{},u=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(Oa(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=u!=null?u:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=q.querySelector("svg");W&&W.setAttribute("stroke",h)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},Xf=()=>{var F,B,se,ae,Z,ve,Fe,Se;if(!q)return;sl();let l=(F=r.voiceRecognition)!=null?F:{},u=_.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",b=(ae=(se=l.processingIconColor)!=null?se:mt==null?void 0:mt.color)!=null?ae:"",T=(ve=(Z=l.processingBackgroundColor)!=null?Z:mt==null?void 0:mt.backgroundColor)!=null?ve:"",W=(Se=(Fe=l.processingBorderColor)!=null?Fe:mt==null?void 0:mt.borderColor)!=null?Se:"";Oa(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=T,q.style.borderColor=W;let z=b||"currentColor";q.style.color=z,al(h,z),q.setAttribute("aria-label","Processing voice input"),u==="none"&&(q.style.cursor="default")},Yf=()=>{var se,ae,Z,ve,Fe,Se,st,je,gt,it,He,Pe;if(!q)return;sl();let l=(se=r.voiceRecognition)!=null?se:{},u=_.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",b=(ae=l.speakingIconName)!=null?ae:h,T=(Se=l.speakingIconColor)!=null?Se:u==="barge-in"?(ve=(Z=l.recordingIconColor)!=null?Z:mt==null?void 0:mt.color)!=null?ve:"":(Fe=mt==null?void 0:mt.color)!=null?Fe:"",W=(gt=l.speakingBackgroundColor)!=null?gt:u==="barge-in"?(st=l.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(je=mt==null?void 0:mt.backgroundColor)!=null?je:"",z=(Pe=l.speakingBorderColor)!=null?Pe:u==="barge-in"?(it=l.recordingBorderColor)!=null?it:"":(He=mt==null?void 0:mt.borderColor)!=null?He:"";Oa(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=W,q.style.borderColor=z;let F=T||"currentColor";q.style.color=F,al(b,F);let B=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",B),u==="none"&&(q.style.cursor="default"),u==="barge-in"&&q.classList.add("persona-voice-recording")},qr=()=>{var l,u,h;q&&(Oa(),mt&&(q.style.backgroundColor=(l=mt.backgroundColor)!=null?l:"",q.style.color=(u=mt.color)!=null?u:"",q.style.borderColor=(h=mt.borderColor)!=null?h:"",al(mt.iconName,mt.color||"currentColor"),mt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},Fa=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Wn(),rr("user"),qr()});return}_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),ht.manuallyDeactivated=!_.isVoiceActive(),Wn(),rr("user"),_.isVoiceActive()?us():qr()});return}if(Pr){let h=Te.value.trim();ht.manuallyDeactivated=!0,Wn(),uo("user"),h&&(Te.value="",Te.style.height="auto",_.sendMessage(h))}else ht.manuallyDeactivated=!1,Wn(),Na("user")};Nn=Fa,q&&(q.addEventListener("click",Fa),dt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),qr()):uo("system"),q&&q.removeEventListener("click",Fa)}));let Zf=o.on("assistant:complete",()=>{_s&&(ht.active||ht.manuallyDeactivated||_s==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!ht.active&&!ht.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),rr("auto"),_.isVoiceActive()&&us()}):Na("auto"))},600))});dt.push(Zf);let eh=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(eh);let Wc=()=>{$t(!L,"user")},Xt=null,ln=null;if(S&&!D()){let{instance:l,element:u}=ql({config:r,plugins:s,onToggle:Wc});Xt=l,l||(ln=u)}Xt?e.appendChild(Xt.element):ln&&e.appendChild(ln),zs(),os(),Tc(),el(_.isStreaming()),rt()==="follow"?Hn(!0):po(),Ha(),O&&(!S||D()?setTimeout(()=>tl(),0):L&&setTimeout(()=>tl(),200));let Vs=()=>{var B,se,ae,Z,ve,Fe,Se,st,je,gt,it,He,Pe,qe,Je,bt,P,Ne,Be,fe,Ot,Dt;if(D()){In(),zs();return}let l=on(r),u=(se=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?se:!1,h=l||u||((Z=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Z:!1),b=(ve=e.ownerDocument.defaultView)!=null?ve:window,T=(Se=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Se:!0,W=(je=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?je:640,z=b.innerWidth<=W,F=T&&z&&S;try{if(F){be(),So(e,r);return}if(H&&(H=!1,be(),So(e,r)),!S&&!l){de.style.height="",de.style.width="";return}if(!u&&!l){let zt=(it=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?it:r==null?void 0:r.launcherWidth,wt=zt!=null?zt:Qn;de.style.width=wt,de.style.maxWidth=wt}if(Sr(),!h){let zt=b.innerHeight,wt=64,jt=(Pe=(He=r.launcher)==null?void 0:He.heightOffset)!=null?Pe:0,Kn=Math.max(200,zt-wt),Yt=Math.min(640,Kn),Xe=Math.max(200,Yt-jt);de.style.height=`${Xe}px`}}finally{if(In(),zs(),L&&S){let wt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((bt=(Je=r.launcher)==null?void 0:Je.mobileBreakpoint)!=null?bt:640),jt=(Ne=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Ne:!1,Kn=(fe=(Be=r.launcher)==null?void 0:Be.mobileFullscreen)!=null?fe:!0,Yt=on(r)&&Kn&&wt,Xe=jt||Kn&&wt&&S||Yt;if(Xe&&!an){let kt=e.getRootNode(),rn=kt instanceof ShadowRoot?kt.host:e.closest(".persona-host");rn&&!Qt&&(Qt=Ol(rn,(Dt=(Ot=r.launcher)==null?void 0:Ot.zIndex)!=null?Dt:Cn)),an=Fl(e.ownerDocument)}else Xe||(Qt==null||Qt(),Qt=null,an==null||an(),an=null)}}};Vs();let Hc=(Nd=e.ownerDocument.defaultView)!=null?Nd:window;if(Hc.addEventListener("resize",Vs),dt.push(()=>Hc.removeEventListener("resize",Vs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{In()});l.observe(Re),dt.push(()=>l.disconnect())}qn=Ce.scrollTop;let Bc=Xr(Ce),th=()=>{let l=Ce.getRootNode(),u=typeof l.getSelection=="function"?l.getSelection():null;return u!=null?u:Ce.ownerDocument.getSelection()},il=()=>cg(th(),Ce),Dc=()=>{let l=Ce.scrollTop,u=Xr(Ce),h=u<Bc;if(Bc=u,rt()!=="follow"){qn=l,Ze();return}let{action:b,nextLastScrollTop:T}=bi({following:Un.isFollowing(),currentScrollTop:l,lastScrollTop:qn,nearBottom:Yo(Ce,ls),userScrollThreshold:Ra,isAutoScrolling:mr||Ho||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qn=T,b==="resume"){il()||jr();return}b==="pause"&&Mt()};if(Ce.addEventListener("scroll",Dc,{passive:!0}),dt.push(()=>Ce.removeEventListener("scroll",Dc)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Vn()});l.observe(Ve),l.observe(Ce),dt.push(()=>l.disconnect())}let Nc=()=>{rt()==="follow"&&Un.isFollowing()&&il()&&Mt()},Oc=Ce.ownerDocument;Oc.addEventListener("selectionchange",Nc),dt.push(()=>{Oc.removeEventListener("selectionchange",Nc)});let Fc=l=>{if(rt()!=="follow")return;let u=xi({following:Un.isFollowing(),deltaY:l.deltaY,nearBottom:Yo(Ce,ls),resumeWhenNearBottom:!0});u==="pause"?Mt():u==="resume"&&!il()&&jr()};Ce.addEventListener("wheel",Fc,{passive:!0}),dt.push(()=>Ce.removeEventListener("wheel",Fc)),ct.addEventListener("click",()=>{fn(),Ce.scrollTop=Ce.scrollHeight,qn=Ce.scrollTop,jr(),Hn(!0),Ze()}),dt.push(()=>ct.remove()),dt.push(()=>{$(),fn()});let _c=()=>{Ke&&(Tr&&(Ke.removeEventListener("click",Tr),Tr=null),N()?(Ke.style.display="",Tr=()=>{$t(!1,"user")},Ke.addEventListener("click",Tr)):Ke.style.display="none")};_c(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Mr.clear(),jr(),xo(Y.composerOverlay);try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),ce==null||ce.clear(),oe==null||oe.reset(),J==null||J.update()})})(),It&&It.addEventListener("submit",Mc),Te==null||Te.addEventListener("keydown",Lc),Te==null||Te.addEventListener("input",kc),Te==null||Te.addEventListener("paste",Ic);let $c=(Od=e.ownerDocument)!=null?Od:document;$c.addEventListener("keydown",Pc,!0);let jc="persona-attachment-drop-active",Ks=0,ll=()=>{Ks=0,pe.classList.remove(jc)},ms=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&vt!==null},Uc=l=>{!zi(l.dataTransfer)||!ms()||(Ks++,Ks===1&&pe.classList.add(jc))},qc=l=>{!zi(l.dataTransfer)||!ms()||(Ks--,Ks<=0&&ll())},zc=l=>{!zi(l.dataTransfer)||!ms()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Vc=l=>{var h;if(!zi(l.dataTransfer)||!ms())return;l.preventDefault(),l.stopPropagation(),ll();let u=Array.from((h=l.dataTransfer.files)!=null?h:[]);u.length!==0&&vt.handleFiles(u)},mo=!0;pe.addEventListener("dragenter",Uc,mo),pe.addEventListener("dragleave",qc,mo),e.addEventListener("dragover",zc,mo),e.addEventListener("drop",Vc,mo);let _a=e.ownerDocument,Kc=l=>{ms()&&l.preventDefault()},Gc=l=>{ms()&&l.preventDefault()};_a.addEventListener("dragover",Kc),_a.addEventListener("drop",Gc),dt.push(()=>{It&&It.removeEventListener("submit",Mc),Te==null||Te.removeEventListener("keydown",Lc),Te==null||Te.removeEventListener("input",kc),Te==null||Te.removeEventListener("paste",Ic),$c.removeEventListener("keydown",Pc,!0)}),dt.push(()=>{pe.removeEventListener("dragenter",Uc,mo),pe.removeEventListener("dragleave",qc,mo),e.removeEventListener("dragover",zc,mo),e.removeEventListener("drop",Vc,mo),_a.removeEventListener("dragover",Kc),_a.removeEventListener("drop",Gc),ll()}),dt.push(()=>{_.cancel()}),Xt?dt.push(()=>{Xt==null||Xt.destroy()}):ln&&dt.push(()=>{ln==null||ln.remove()});let nn={update(l){var xn,En,Ir,un,Mn,kn,$o,Gs,zd,Vd,Kd,Gd,Jd,Qd,Xd,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,Sp,Ap,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Su,Au,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu;let u=r.toolCall,h=r.messageActions,b=(xn=r.layout)==null?void 0:xn.messages,T=r.colorScheme,W=r.loadingIndicator,z=r.iterationDisplay,F=(En=r.features)==null?void 0:En.showReasoning,B=(Ir=r.features)==null?void 0:Ir.showToolCalls,se=(un=r.features)==null?void 0:un.toolCallDisplay,ae=(Mn=r.features)==null?void 0:Mn.reasoningDisplay;r={...r,...l},be(),So(e,r),Di(e,r),Ni(e,r),jn(),r.colorScheme!==T&&Fs();let Z=Ea.getForInstance(r.plugins);s.length=0,s.push(...Z),S=($o=(kn=r.launcher)==null?void 0:kn.enabled)!=null?$o:!0,R=(zd=(Gs=r.launcher)==null?void 0:Gs.autoExpand)!=null?zd:!1,Ue=(Kd=(Vd=r.features)==null?void 0:Vd.showReasoning)!=null?Kd:!0,Ae=(Jd=(Gd=r.features)==null?void 0:Gd.showToolCalls)!=null?Jd:!0,_e=(Xd=(Qd=r.features)==null?void 0:Qd.scrollToBottom)!=null?Xd:{};let ve=rt();ye=(Zd=(Yd=r.features)==null?void 0:Yd.scrollBehavior)!=null?Zd:{},ve!==rt()&&(fn(),jr()),vr(),Ze();let Fe=Le;if(Le=(tp=(ep=r.features)==null?void 0:ep.showEventStreamToggle)!=null?tp:!1,Le&&!Fe){if(ce||(X=new Aa(ie),ce=new Sa(re,X),oe=oe!=null?oe:new Ta,X.open().then(()=>ce==null?void 0:ce.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Tt)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,ee,Tt),oe==null||oe.processEvent(ee,Tt),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&Ee){let ee=(rp=(np=r.features)==null?void 0:np.eventStream)==null?void 0:rp.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"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=y("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Ut=xe("activity","18px","currentColor",1.5);Ut&&yt.appendChild(Ut);let lt=Y.clearChatButtonWrapper,Lt=Y.closeButtonWrapper,dn=lt||Lt;dn&&dn.parentNode===Ee?Ee.insertBefore(yt,dn):Ee.appendChild(yt),yt.addEventListener("click",()=>{te?dr():Br()})}}else!Le&&Fe&&(dr(),yt&&(yt.remove(),yt=null),ce==null||ce.clear(),X==null||X.destroy(),ce=null,X=null,oe==null||oe.reset(),oe=null);if(((op=r.launcher)==null?void 0:op.enabled)===!1&&Xt&&(Xt.destroy(),Xt=null),((sp=r.launcher)==null?void 0:sp.enabled)===!1&&ln&&(ln.remove(),ln=null),((ap=r.launcher)==null?void 0:ap.enabled)!==!1&&!Xt&&!ln){let{instance:ee,element:Tt}=ql({config:r,plugins:s,onToggle:Wc});Xt=ee,ee||(ln=Tt),e.appendChild(Tt)}Xt&&Xt.update(r),me&&((ip=r.launcher)==null?void 0:ip.title)!==void 0&&(me.textContent=r.launcher.title),ke&&((lp=r.launcher)==null?void 0:lp.subtitle)!==void 0&&(ke.textContent=r.launcher.subtitle);let Se=(cp=r.layout)==null?void 0:cp.header;if((Se==null?void 0:Se.layout)!==A&&Ee){let ee=Se?Is(r,Se,{showClose:N(),onClose:()=>$t(!1,"user")}):Yr({config:r,showClose:N(),onClose:()=>$t(!1,"user")});Ge.replaceHeader(ee),Ee=Ge.header.element,E=Ge.header.iconHolder,me=Ge.header.headerTitle,ke=Ge.header.headerSubtitle,Ke=Ge.header.closeButton,A=Se==null?void 0:Se.layout}else if(Se&&(E&&(E.style.display=Se.showIcon===!1?"none":""),me&&(me.style.display=Se.showTitle===!1?"none":""),ke&&(ke.style.display=Se.showSubtitle===!1?"none":""),Ke&&(Ke.style.display=Se.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let ee=Se.showClearChat;if(ee!==void 0){Y.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=Y;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let je=((dp=r.layout)==null?void 0:dp.showHeader)!==!1;Ee&&(Ee.style.display=je?"":"none");let gt=((pp=r.layout)==null?void 0:pp.showFooter)!==!1;Re&&(Re.style.display=gt?"":"none"),In(),Ze(),S!==I?S?$t(R,"auto"):(L=!0,zs()):R!==k&&$t(R,"auto"),k=R,I=S,Vs(),_c();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(u),qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),Je=JSON.stringify((up=r.layout)==null?void 0:up.messages)!==JSON.stringify(b),bt=((mp=r.loadingIndicator)==null?void 0:mp.render)!==(W==null?void 0:W.render)||((gp=r.loadingIndicator)==null?void 0:gp.renderIdle)!==(W==null?void 0:W.renderIdle)||((fp=r.loadingIndicator)==null?void 0:fp.showBubble)!==(W==null?void 0:W.showBubble),P=r.iterationDisplay!==z,Ne=((yp=(hp=r.features)==null?void 0:hp.showReasoning)!=null?yp:!0)!==(F!=null?F:!0)||((xp=(bp=r.features)==null?void 0:bp.showToolCalls)!=null?xp:!0)!==(B!=null?B:!0)||JSON.stringify((vp=r.features)==null?void 0:vp.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((wp=r.features)==null?void 0:wp.reasoningDisplay)!==JSON.stringify(ae);(Pe||qe||Je||bt||P||Ne)&&_&&(ss++,$s(Ve,_.getMessages(),Ie));let fe=(Cp=r.launcher)!=null?Cp:{},Ot=(Sp=fe.headerIconHidden)!=null?Sp:!1,Dt=(Tp=(Ap=r.layout)==null?void 0:Ap.header)==null?void 0:Tp.showIcon,zt=Ot||Dt===!1,wt=fe.headerIconName,jt=(Ep=fe.headerIconSize)!=null?Ep:"48px";if(E){let ee=pe.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(zt)E.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(E.style.display="",E.style.height=jt,E.style.width=jt,ee&&Tt&&(ee.contains(E)?E.nextSibling!==Tt&&(E.remove(),ee.insertBefore(E,Tt)):ee.insertBefore(E,Tt)),wt){let lt=parseFloat(jt)||24,Lt=xe(wt,lt*.6,"currentColor",1);Lt?E.replaceChildren(Lt):E.textContent=(Mp=fe.agentIconText)!=null?Mp:"\u{1F4AC}"}else if(fe.iconUrl){let lt=E.querySelector("img");if(lt)lt.src=fe.iconUrl,lt.style.height=jt,lt.style.width=jt;else{let Lt=document.createElement("img");Lt.src=fe.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=jt,Lt.style.width=jt,E.replaceChildren(Lt)}}else{let lt=E.querySelector("svg"),Lt=E.querySelector("img");(lt||Lt)&&E.replaceChildren(),E.textContent=(kp=fe.agentIconText)!=null?kp:"\u{1F4AC}"}let Ut=E.querySelector("img");Ut&&(Ut.style.height=jt,Ut.style.width=jt)}}let Kn=(Pp=(Lp=r.layout)==null?void 0:Lp.header)==null?void 0:Pp.showTitle,Yt=(Rp=(Ip=r.layout)==null?void 0:Ip.header)==null?void 0:Rp.showSubtitle;if(me&&(me.style.display=Kn===!1?"none":""),ke&&(ke.style.display=Yt===!1?"none":""),Ke){((Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showCloseButton)===!1?Ke.style.display="none":Ke.style.display="";let Tt=(Bp=fe.closeButtonSize)!=null?Bp:"32px",Ut=(Dp=fe.closeButtonPlacement)!=null?Dp:"inline";Ke.style.height=Tt,Ke.style.width=Tt;let{closeButtonWrapper:lt}=Y,Lt=Ut==="top-right",dn=lt==null?void 0:lt.classList.contains("persona-absolute");if(lt&&Lt!==dn)if(lt.remove(),Lt)lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(lt);else{let pt=(Op=(Np=fe.clearChat)==null?void 0:Np.placement)!=null?Op:"inline",pn=(_p=(Fp=fe.clearChat)==null?void 0:Fp.enabled)!=null?_p:!0;lt.className=pn&&pt==="inline"?"":"persona-ml-auto";let Dn=pe.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(lt)}if(Ke.style.color=fe.closeButtonColor||Pn.actionIconColor,fe.closeButtonBackgroundColor?(Ke.style.backgroundColor=fe.closeButtonBackgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let pt=fe.closeButtonBorderWidth||"0px",pn=fe.closeButtonBorderColor||"transparent";Ke.style.border=`${pt} solid ${pn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");fe.closeButtonBorderRadius?(Ke.style.borderRadius=fe.closeButtonBorderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(Ke.style.paddingLeft=fe.closeButtonPaddingX,Ke.style.paddingRight=fe.closeButtonPaddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),fe.closeButtonPaddingY?(Ke.style.paddingTop=fe.closeButtonPaddingY,Ke.style.paddingBottom=fe.closeButtonPaddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let vn=($p=fe.closeButtonIconName)!=null?$p:"x",fr=(jp=fe.closeButtonIconText)!=null?jp:"\xD7";Ke.innerHTML="";let Ln=xe(vn,"28px","currentColor",1);Ln?Ke.appendChild(Ln):Ke.textContent=fr;let Jt=(Up=fe.closeButtonTooltipText)!=null?Up:"Close chat",Jn=(qp=fe.closeButtonShowTooltip)!=null?qp:!0;if(Ke.setAttribute("aria-label",Jt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Jn&&Jt)){let pt=null,pn=()=>{if(pt||!Ke)return;let jo=Ke.ownerDocument,Js=jo.body;if(!Js)return;pt=Wr(jo,"div","persona-clear-chat-tooltip"),pt.textContent=Jt;let Qs=Wr(jo,"div");Qs.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Qs);let Uo=Ke.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Ao),pt.style.left=`${Uo.left+Uo.width/2}px`,pt.style.top=`${Uo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Js.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",pn),lt.addEventListener("mouseleave",Dn),Ke.addEventListener("focus",pn),Ke.addEventListener("blur",Dn),lt._cleanupTooltip=()=>{Dn(),lt&&(lt.removeEventListener("mouseenter",pn),lt.removeEventListener("mouseleave",Dn)),Ke&&(Ke.removeEventListener("focus",pn),Ke.removeEventListener("blur",Dn))}}}let{clearChatButton:Xe,clearChatButtonWrapper:kt}=Y;if(Xe){let ee=(zp=fe.clearChat)!=null?zp:{},Tt=(Vp=ee.enabled)!=null?Vp:!0,Ut=(Gp=(Kp=r.layout)==null?void 0:Kp.header)==null?void 0:Gp.showClearChat,lt=Ut!==void 0?Ut:Tt,Lt=(Jp=ee.placement)!=null?Jp:"inline";if(kt){kt.style.display=lt?"":"none";let{closeButtonWrapper:dn}=Y;!D()&&dn&&!dn.classList.contains("persona-absolute")&&(lt?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let vn=Lt==="top-right",fr=kt.classList.contains("persona-absolute");if(!D()&&vn!==fr&<){if(kt.remove(),vn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",pe.style.position="relative",pe.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let Jt=pe.querySelector(".persona-border-b-persona-divider"),Jn=Y.closeButtonWrapper;Jt&&Jn&&Jn.parentElement===Jt?Jt.insertBefore(kt,Jn):Jt&&Jt.appendChild(kt)}let Ln=Y.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(lt){if(!D()){let pt=(Qp=ee.size)!=null?Qp:"32px";Xe.style.height=pt,Xe.style.width=pt}let dn=(Xp=ee.iconName)!=null?Xp:"refresh-cw",vn=(Yp=ee.iconColor)!=null?Yp:"";Xe.style.color=vn||Pn.actionIconColor,Xe.innerHTML="";let fr=D()?"14px":"20px",Ln=xe(dn,fr,"currentColor",2);if(Ln&&Xe.appendChild(Ln),ee.backgroundColor?(Xe.style.backgroundColor=ee.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let pt=ee.borderWidth||"0px",pn=ee.borderColor||"transparent";Xe.style.border=`${pt} solid ${pn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");ee.borderRadius?(Xe.style.borderRadius=ee.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),ee.paddingX?(Xe.style.paddingLeft=ee.paddingX,Xe.style.paddingRight=ee.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),ee.paddingY?(Xe.style.paddingTop=ee.paddingY,Xe.style.paddingBottom=ee.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Jt=(Zp=ee.tooltipText)!=null?Zp:"Clear chat",Jn=(eu=ee.showTooltip)!=null?eu:!0;if(Xe.setAttribute("aria-label",Jt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Jn&&Jt)){let pt=null,pn=()=>{if(pt||!Xe)return;let jo=Xe.ownerDocument,Js=jo.body;if(!Js)return;pt=Wr(jo,"div","persona-clear-chat-tooltip"),pt.textContent=Jt;let Qs=Wr(jo,"div");Qs.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Qs);let Uo=Xe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Ao),pt.style.left=`${Uo.left+Uo.width/2}px`,pt.style.top=`${Uo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Js.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};kt.addEventListener("mouseenter",pn),kt.addEventListener("mouseleave",Dn),Xe.addEventListener("focus",pn),Xe.addEventListener("blur",Dn),kt._cleanupTooltip=()=>{Dn(),kt&&(kt.removeEventListener("mouseenter",pn),kt.removeEventListener("mouseleave",Dn)),Xe&&(Xe.removeEventListener("focus",pn),Xe.removeEventListener("blur",Dn))}}}}let rn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ma],ar=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];M=ka({parsers:rn,handlers:ar,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Yg(r,M,ne),_.updateConfig(r),$s(Ve,_.getMessages(),Ie),os(),Tc(),el(_.isStreaming());let Gn=((tu=r.voiceRecognition)==null?void 0:tu.enabled)===!0,No=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Oo=((ru=(nu=r.voiceRecognition)==null?void 0:nu.provider)==null?void 0:ru.type)==="runtype";if(Gn&&(No||Oo))if(!q||!at){let ee=Qf(r.voiceRecognition,r.sendButton);ee&&(q=ee.micButton,at=ee.micButtonWrapper,ut.insertBefore(at,hn),q.addEventListener("click",Fa),q.disabled=_.isStreaming())}else{let ee=(ou=r.voiceRecognition)!=null?ou:{},Tt=(su=r.sendButton)!=null?su:{},Ut=(au=ee.iconName)!=null?au:"mic",lt=(iu=Tt.size)!=null?iu:"40px",Lt=(lu=ee.iconSize)!=null?lu:lt,dn=parseFloat(Lt)||24;q.style.width=Lt,q.style.height=Lt,q.style.minWidth=Lt,q.style.minHeight=Lt;let vn=(du=(cu=ee.iconColor)!=null?cu:Tt.textColor)!=null?du:"currentColor";q.innerHTML="";let fr=xe(Ut,dn,vn,2);fr?q.appendChild(fr):q.textContent="\u{1F3A4}";let Ln=(pu=ee.backgroundColor)!=null?pu:Tt.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn:q.style.color="var(--persona-text, #111827)",ee.borderWidth?(q.style.borderWidth=ee.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),ee.borderColor?q.style.borderColor=ee.borderColor:q.style.borderColor="",ee.paddingX?(q.style.paddingLeft=ee.paddingX,q.style.paddingRight=ee.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),ee.paddingY?(q.style.paddingTop=ee.paddingY,q.style.paddingBottom=ee.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Jt=at==null?void 0:at.querySelector(".persona-send-button-tooltip"),Jn=(uu=ee.tooltipText)!=null?uu:"Start voice recognition";if(((mu=ee.showTooltip)!=null?mu:!1)&&Jn)if(Jt)Jt.textContent=Jn,Jt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=Jn,at==null||at.insertBefore(pn,q)}else Jt&&(Jt.style.display="none");at.style.display="",q.disabled=_.isStreaming()}else q&&at&&(at.style.display="none",((fu=(gu=r.voiceRecognition)==null?void 0:gu.provider)==null?void 0:fu.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Pr&&uo());if(((hu=r.attachments)==null?void 0:hu.enabled)===!0)if(!ue||!K){let ee=(yu=r.attachments)!=null?yu:{},Ut=(xu=((bu=r.sendButton)!=null?bu:{}).size)!=null?xu:"40px";xt||(xt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xt.style.display="none",It.insertBefore(xt,Te)),Me||(Me=document.createElement("input"),Me.type="file",Me.accept=((vu=ee.allowedTypes)!=null?vu:Qr).join(","),Me.multiple=((wu=ee.maxFiles)!=null?wu:4)>1,Me.style.display="none",Me.setAttribute("aria-label","Attach files"),It.insertBefore(Me,Te)),ue=y("div","persona-send-button-wrapper"),K=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),K.type="button",K.setAttribute("aria-label",(Cu=ee.buttonTooltipText)!=null?Cu:"Attach file");let lt=(Su=ee.buttonIconName)!=null?Su:"paperclip",Lt=Ut,dn=parseFloat(Lt)||40,vn=Math.round(dn*.6);K.style.width=Lt,K.style.height=Lt,K.style.minWidth=Lt,K.style.minHeight=Lt,K.style.fontSize="18px",K.style.lineHeight="1",K.style.backgroundColor="transparent",K.style.color="var(--persona-primary, #111827)",K.style.border="none",K.style.borderRadius="6px",K.style.transition="background-color 0.15s ease",K.addEventListener("mouseenter",()=>{K.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),K.addEventListener("mouseleave",()=>{K.style.backgroundColor="transparent"});let fr=xe(lt,vn,"currentColor",1.5);fr?K.appendChild(fr):K.textContent="\u{1F4CE}",K.addEventListener("click",Jn=>{Jn.preventDefault(),Me==null||Me.click()}),ue.appendChild(K);let Ln=(Au=ee.buttonTooltipText)!=null?Au:"Attach file",Jt=y("div","persona-send-button-tooltip");Jt.textContent=Ln,ue.appendChild(Jt),Qe.append(ue),!vt&&Me&&xt&&(vt=Xo.fromConfig(ee),vt.setPreviewsContainer(xt),Me.addEventListener("change",async()=>{vt&&(Me!=null&&Me.files)&&(await vt.handleFileSelect(Me.files),Me.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(Zg(ee.dropOverlay))}else{ue.style.display="";let ee=(Tu=r.attachments)!=null?Tu:{};Me&&(Me.accept=((Eu=ee.allowedTypes)!=null?Eu:Qr).join(","),Me.multiple=((Mu=ee.maxFiles)!=null?Mu:4)>1),vt&&vt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ue&&(ue.style.display="none"),vt&&vt.clearAttachments(),(ku=pe.querySelector(".persona-attachment-drop-overlay"))==null||ku.remove();let Vt=(Lu=r.sendButton)!=null?Lu:{},Fo=(Pu=Vt.useIcon)!=null?Pu:!1,go=(Iu=Vt.iconText)!=null?Iu:"\u2191",fo=Vt.iconName,zr=(Ru=Vt.tooltipText)!=null?Ru:"Send message",_o=(Wu=Vt.showTooltip)!=null?Wu:!1,gr=(Hu=Vt.size)!=null?Hu:"40px",et=Vt.backgroundColor,cn=Vt.textColor;if(Fo){if(ge.style.width=gr,ge.style.height=gr,ge.style.minWidth=gr,ge.style.minHeight=gr,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.innerHTML="",cn?ge.style.color=cn:ge.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let ee=parseFloat(gr)||24,Tt=(cn==null?void 0:cn.trim())||"currentColor",Ut=xe(fo,ee,Tt,2);Ut?ge.appendChild(Ut):ge.textContent=go}else ge.textContent=go;ge.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",et?(ge.style.backgroundColor=et,ge.classList.remove("persona-bg-persona-primary")):(ge.style.backgroundColor="",ge.classList.add("persona-bg-persona-primary"))}else ge.textContent=(Du=(Bu=r.copy)==null?void 0:Bu.sendButtonLabel)!=null?Du:"Send",ge.style.width="",ge.style.height="",ge.style.minWidth="",ge.style.minHeight="",ge.style.fontSize="",ge.style.lineHeight="",ge.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",et?(ge.style.backgroundColor=et,ge.classList.remove("persona-bg-persona-accent")):ge.classList.add("persona-bg-persona-accent"),cn?ge.style.color=cn:ge.classList.add("persona-text-white");Vt.borderWidth?(ge.style.borderWidth=Vt.borderWidth,ge.style.borderStyle="solid"):(ge.style.borderWidth="",ge.style.borderStyle=""),Vt.borderColor?ge.style.borderColor=Vt.borderColor:ge.style.borderColor="",Vt.paddingX?(ge.style.paddingLeft=Vt.paddingX,ge.style.paddingRight=Vt.paddingX):(ge.style.paddingLeft="",ge.style.paddingRight=""),Vt.paddingY?(ge.style.paddingTop=Vt.paddingY,ge.style.paddingBottom=Vt.paddingY):(ge.style.paddingTop="",ge.style.paddingBottom="");let _t=hn==null?void 0:hn.querySelector(".persona-send-button-tooltip");if(_o&&zr)if(_t)_t.textContent=zr,_t.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=zr,hn==null||hn.insertBefore(ee,ge)}else _t&&(_t.style.display="none");let Ft=($u=(Nu=r.layout)==null?void 0:Nu.contentMaxWidth)!=null?$u:D()?(_u=(Fu=(Ou=r.launcher)==null?void 0:Ou.composerBar)==null?void 0:Fu.contentMaxWidth)!=null?_u:"720px":void 0;Ft?(Ve.style.maxWidth=Ft,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",It&&(It.style.maxWidth=Ft,It.style.marginLeft="auto",It.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Ft,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let ft=(ju=r.statusIndicator)!=null?ju:{},Kt=(Uu=ft.visible)!=null?Uu:!0;if(sn.style.display=Kt?"":"none",_){let ee=_.getStatus();Ye(sn,(Ut=>{var lt,Lt,dn,vn;return Ut==="idle"?(lt=ft.idleText)!=null?lt:wn.idle:Ut==="connecting"?(Lt=ft.connectingText)!=null?Lt:wn.connecting:Ut==="connected"?(dn=ft.connectedText)!=null?dn:wn.connected:Ut==="error"?(vn=ft.errorText)!=null?vn:wn.error:wn[Ut]})(ee),ft,ee)}sn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";sn.classList.add(St)},open(){N()&&$t(!0,"api")},close(){N()&&$t(!1,"api")},toggle(){N()&&$t(!L,"api")},clearChat(){An=!1,_.clearMessages(),Mr.clear(),jr();try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}d={},M.syncFromMetadata(),ce==null||ce.clear(),oe==null||oe.reset(),J==null||J.update()},setMessage(l){return!Te||_.isStreaming()?!1:(!L&&N()&&$t(!0,"system"),Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let u=(l==null?void 0:l.trim())||Te.value.trim();return u?(!L&&N()&&$t(!0,"system"),Te.value="",Te.style.height="auto",_.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return _.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!L&&N()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Wn(),_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),rr("user"),_.isVoiceActive()&&us()})),!0):Pr?!0:Rc()?(!L&&N()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Wn(),Na("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Wn(),rr("user"),qr()}),!0):!1:Pr?(ht.manuallyDeactivated=!0,Wn(),uo("user"),!0):!1},injectMessage(l){return!L&&N()&&$t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!L&&N()&&$t(!0,"system");let u=_.injectAssistantMessage(l);return U&&(U=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),u},injectUserMessage(l){return!L&&N()&&$t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!L&&N()&&$t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!L&&N()&&$t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!L&&N()&&$t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!L&&N()&&$t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,u){return _.connectStream(l,u)},__pushEventStreamEvent(l){ce&&(oe==null||oe.processEvent(l.type,l.payload),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Le||!ce||Br()},hideEventStream(){te&&dr()},isEventStreamVisible(){return te},showArtifacts(){cr(r)&&(An=!1,jn(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(An=!0,jn())},upsertArtifact(l){return cr(r)?(An=!1,_.upsertArtifact(l)):null},selectArtifact(l){cr(r)&&_.selectArtifact(l)},clearArtifacts(){cr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return S&&!L&&!D()||!Te?!1:(Te.focus(),!0)},async resolveApproval(l,u,h){let T=_.getMessages().find(W=>{var z;return W.variant==="approval"&&((z=W.approval)==null?void 0:z.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){_.resolveWebMcpApproval(T.id,u);return}return _.resolveApproval(T.approval,u,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){g(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return N()&&L},isVoiceActive(){return ht.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:N()&&L,launcherEnabled:S,voiceActive:ht.active,streaming:_.isStreaming()}},showCSATFeedback(l){!L&&N()&&$t(!0,"system");let u=Ve.querySelector(".persona-feedback-container");u&&u.remove();let h=Ui({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!L&&N()&&$t(!0,"system");let u=Ve.querySelector(".persona-feedback-container");u&&u.remove();let h=qi({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return _.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return _.submitNPSFeedback(l,u)},destroy(){Do!=null&&(clearInterval(Do),Do=null),dt.forEach(l=>l()),Oe.remove(),tt==null||tt.remove(),Xt==null||Xt.destroy(),ln==null||ln.remove(),Tr&&Ke.removeEventListener("click",Tr)}};if((((Fd=n==null?void 0:n.debugTools)!=null?Fd:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={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=u,dt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",u),dt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Le){let F=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&nn.showEventStream()},B=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",B),dt.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",B)})}let h=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.showArtifacts()},b=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.hideArtifacts()},T=F=>{let B=F.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&nn.upsertArtifact(B.artifact)},W=F=>{let B=F.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&nn.selectArtifact(B.id)},z=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let sr=Nb(r.persistState);if(sr&&N()){let l=Ob(sr.storage),u=`${sr.keyPrefix}widget-open`,h=`${sr.keyPrefix}widget-voice`,b=`${sr.keyPrefix}widget-voice-mode`;if(l){let T=((_d=sr.persist)==null?void 0:_d.openState)&&l.getItem(u)==="true",W=(($d=sr.persist)==null?void 0:$d.voiceState)&&l.getItem(h)==="true",z=((jd=sr.persist)==null?void 0:jd.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{nn.open(),setTimeout(()=>{var F;if(W||z)nn.startVoiceRecognition();else if((F=sr.persist)!=null&&F.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Ud=sr.persist)!=null&&Ud.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(qd=sr.persist)!=null&&qd.voiceState&&(o.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),o.on("user:message",F=>{l.setItem(b,F.viaVoice?"true":"false")})),sr.clearOnChatClear){let F=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(b)},B=()=>F();window.addEventListener("persona:clear-chat",B),dt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&N()&&setTimeout(()=>{nn.open()},0),ds(),Ia||Xu().then(()=>{_&&(ss++,Mr.clear(),$s(Ve,_.getMessages(),Ie))}).catch(()=>{}),nn};var Fb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},_b=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},$b=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},jb=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ef=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},lc=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=""},tf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",lc(e)},sc=e=>{e.style.transition=""},ac=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=""},ic=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ki=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ub=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},qb=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},nf=(e,t,n,r,s,o,a)=>{var x,v,M,S,R,O;let i=Xn(o),d=i.reveal==="push";Ub(e,t,n,r,d),qb(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,m=(S=(M=o==null?void 0:o.launcher)==null?void 0:M.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=m:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ac(t),sc(r),tf(r),ic(n),Ki(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((O=(R=o==null?void 0:o.launcher)==null?void 0:R.zIndex)!=null?O: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"),tf(r),_b(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ac(t),sc(r),ic(n),Ki(s,r);let k=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=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=A,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",sc(r),lc(r),Ki(s,r);let k=Fb(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),A=i.animate?"margin-left 180ms ease":"none",H=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=A,t.style.marginLeft=`${H}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="",ac(t),lc(r),ic(n),Ki(s,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",H=!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",$b(r,i.maxHeight),r.style.overflow=k||H?"hidden":"visible",r.style.transition=A,k&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},zb=(e,t)=>{let n=e.ownerDocument.createElement("div");return ef(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){ef(n,r)},destroy(){n.remove()}}},Vb=(e,t)=>{var O,k,I,A;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),m=(k=(O=t==null?void 0:t.launcher)==null?void 0:O.enabled)==null||k?(A=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),Xn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{nf(a,i,d,c,p,t,m)}),f.observe(a))},v=!1,M=()=>{nf(a,i,d,c,p,t,m),x(),m&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,jb(a,Xn(t)))},S=a.ownerDocument.defaultView,R=()=>{M()};return S==null||S.addEventListener("resize",R),Xn(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(H){let D=H.launcherEnabled?H.open:!0;m!==D&&(m=D,M())},updateConfig(H){var D,N;t=H,((N=(D=t==null?void 0:t.launcher)==null?void 0:D.enabled)!=null?N:!0)===!1&&(m=!0),M()},destroy(){S==null||S.removeEventListener("resize",R),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},La=(e,t)=>on(t)?Vb(e,t):zb(e,t);var cc={},Kb=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Gb=()=>{try{if(typeof cc!="undefined"&&cc.url)return new URL("../widget.css",cc.url).href}catch{}return null},rf=(e,t)=>{let n=Gb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},dc=e=>{var M;let t=Kb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=La(t,s),a,i=[],d=(S,R)=>{var A,H;let k=!((H=(A=R==null?void 0:R.launcher)==null?void 0:A.enabled)!=null?H:!0)||on(R),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 D=S.attachShadow({mode:"open"});D.appendChild(I),rf(D,r)}else S.appendChild(I),rf(S,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},m=()=>{let S=d(o.host,s);a=Vi(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};m(),(M=e.onChatReady)==null||M.call(e);let g=S=>{f(),o.destroy(),o=La(t,S),s=S,m()},x={update(S){var H,D,N,L,U,V;let R={...s,...S,launcher:{...(H=s==null?void 0:s.launcher)!=null?H:{},...(D=S==null?void 0:S.launcher)!=null?D:{},dock:{...(L=(N=s==null?void 0:s.launcher)==null?void 0:N.dock)!=null?L:{},...(V=(U=S==null?void 0:S.launcher)==null?void 0:U.dock)!=null?V:{}}}},O=on(s),k=on(R),I=Eo(s),A=Eo(R);if(O!==k||I!==A){g(R);return}s=R,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(S,R,O){if(R==="host")return o.host;if(R in S)return Reflect.get(S,R,O);let k=a[R];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var cf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Jb=new Set(["button","a","input","select","textarea","details","summary"]),Qb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),pc=/\b(product|card|item|listing|result)\b/i,mc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Xb=3e3,Yb=100;function df(e){let t=typeof e.className=="string"?e.className:"";if(pc.test(t)||e.id&&pc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&pc.test(r.value))return!0}return!1}function pf(e){var t;return mc.test(((t=e.textContent)!=null?t:"").trim())}function uf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Zb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function of(e){let t=e.match(mc);return t?t[0]:null}function sf(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function ex(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var tx="commerce-card",nx="result-card";function af(e){return!df(e)||!pf(e)||!uf(e)&&!Zb(e)?0:5200}function lf(e){var r;return!df(e)||pf(e)||!uf(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 gc=[{id:tx,scoreElement(e){return af(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||mc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(af(e)===0)return null;let{title:n,href:r}=sf(e),s=(p=(c=of(((d=e.textContent)!=null?d:"").trim()))!=null?c:of(t.text))!=null?p:"",o=ex(e);return[r&&n?`[${n}](${r})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
110
|
-
`)}},{id:
|
|
111
|
-
`)}}];function
|
|
111
|
+
`}if(!b&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Ft=u?"":"padding-top: 1.25em !important;",ft=u?"":`z-index: ${(cn=(et=r.launcher)==null?void 0:et.zIndex)!=null?cn:Cn} !important;`;Oe.style.cssText+=_t+Ft+ft}Je()};be(),So(e,r),Di(e,r),Ni(e,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",ao)});let Qt=null,an=null;dt.push(()=>{Qt==null||Qt(),Qt=null,an==null||an(),an=null}),On&&dt.push(()=>{On==null||On.disconnect(),On=null}),dt.push(()=>{Tn==null||Tn(),Tn=null,Or(),Bt&&(Bt.remove(),Bt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Le&&dt.push(()=>{ze!==null&&(cancelAnimationFrame(ze),ze=null),J==null||J.destroy(),J=null,ce==null||ce.destroy(),ce=null,X=null});let Ar=null,Fs=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=gi(()=>{So(e,r)}))};Fs(),dt.push(()=>{Ar&&(Ar(),Ar=null)});let Fr=(Rd=r.features)==null?void 0:Rd.streamAnimation;if(Fr!=null&&Fr.type&&Fr.type!=="none"){let l=ha(Fr.type,Fr.plugins);l&&(Nl(l,e),dt.push(()=>wg(e)))}let Wo=Dg(Pt),Tr=null,_,os=l=>{var b,T;if(!_)return;let u=l!=null?l:_.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?Ga(u):null;h?Wo.render(h,_,Te,u,r.suggestionChipsConfig,{agentPushed:!0}):u.some(W=>W.role==="user")?Wo.render([],_,Te,u):Wo.render(r.suggestionChips,_,Te,u,r.suggestionChipsConfig)},Er=!1,Mr=cg(),_r=new Map,kr=new Map,pr=new Map,ss=0,Ia=qo()!==null,Un=yi(),qn=0,ur=null,mr=!1,Ho=!1,$r=0,bn=null,Lr=null,as=!1,Bo=!1,is=null,Ra=4,ls=24,Wa=80,cs=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},_s=(Hd=(Wd=r.voiceRecognition)==null?void 0:Wd.autoResume)!=null?Hd:!1,rr=l=>{o.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},Wn=()=>{g(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},Ha=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=oc(d.voiceState),u=!!l.active,h=Number((T=l.timestamp)!=null?T:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<$b&&setTimeout(()=>{var W,z;ht.active||(ht.manuallyDeactivated=!1,((z=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:z.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),rr("restore"),_.isVoiceActive()&&us()}):Na("restore"))},1e3)},Ba=()=>_?tf(_.getMessages()).filter(l=>!l.__skipPersist):[];function co(l){if(!(i!=null&&i.save))return;let h={messages:l?tf(l):_?Ba():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let ot=null,w=()=>Oe.querySelector("#persona-scroll-container")||Ce,j=()=>{ot!==null&&(cancelAnimationFrame(ot),ot=null),mr=!1},$=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),Ho=!1,j()},G=()=>{$r>0?(Sn.textContent=String($r),Sn.style.display="",ct.setAttribute("aria-label",`${en()||"Jump to latest"} (${$r} new)`)):(Sn.textContent="",Sn.style.display="none",ct.setAttribute("aria-label",en()||"Jump to latest"))},he=()=>{$r!==0&&($r=0,G())},$e=()=>rt()==="follow"?!Un.isFollowing():!Yo(Ce,ls),Ze=()=>{if(!Ht()||te){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==pe&&pe.appendChild(ct),In();let u=Xr(Ce)>0&&$e();u||he(),ct.style.display=u?"":"none"},Mt=()=>{Un.pause()&&($(),Ze())},jr=()=>{Un.resume(),he(),Ze()},Hn=(l=!1)=>{rt()==="follow"&&Un.isFollowing()&&(!l&&!Er||(ur!==null&&(cancelAnimationFrame(ur),ur=null),Ho=!0,ur=requestAnimationFrame(()=>{ur=null,Ho=!1,Un.isFollowing()&&gn(w(),l?220:140)})))},zn=(l,u,h,b=()=>!0)=>{let T=l.scrollTop,W=u(),z=W-T;j();let F=performance.now();mr=!0;let B=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!b()){j();return}let Z=u();Z!==W&&(W=Z,z=W-T);let ve=ae-F,Fe=Math.min(ve/h,1),Se=B(Fe),st=T+z*Se;l.scrollTop=st,qn=l.scrollTop,Fe<1?ot=requestAnimationFrame(se):(l.scrollTop=W,qn=l.scrollTop,ot=null,mr=!1)};ot=requestAnimationFrame(se)},gn=(l,u=500)=>{let h=Xr(l)-l.scrollTop;if(Math.abs(h)<1){qn=l.scrollTop;return}if(Math.abs(h)>=Wa){j(),mr=!0,l.scrollTop=Xr(l),qn=l.scrollTop,mr=!1;return}zn(l,()=>Xr(l),u,()=>Un.isFollowing())},po=()=>{let l=w();mr=!0,l.scrollTop=Xr(l),qn=l.scrollTop,mr=!1,Ze()},Ur=l=>{tn.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},fn=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),j(),bn=null,tn.style.height="0px"},Bn=l=>{Lr!==null&&cancelAnimationFrame(Lr),Lr=requestAnimationFrame(()=>{var se;Lr=null;let u=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Ce.querySelector(`[data-message-id="${u}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Ce;)b+=T.offsetTop,T=T.offsetParent;let W=(se=bn==null?void 0:bn.spacerHeight)!=null?se:0,z=Ce.scrollHeight-W,{targetScrollTop:F,spacerHeight:B}=gg({anchorOffsetTop:b,topOffset:Wt(),viewportHeight:Ce.clientHeight,contentHeight:z});bn={initialSpacerHeight:B,contentHeightAtAnchor:z,spacerHeight:B},Ur(B),zn(Ce,()=>F,220)})},Vn=()=>{if(rt()==="follow"){if(!Un.isFollowing()||Yo(Ce,1))return;Hn(!Er);return}if(bn&&bn.initialSpacerHeight>0){let l=Ce.scrollHeight-bn.spacerHeight,u=fg({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});u!==bn.spacerHeight&&Ur(u)}Ze()},Uf=l=>{let u=rt();u==="follow"?(jr(),Hn(!0)):u==="anchor-top"&&Bn(l)},qf=l=>{let u=new Map;l.forEach(h=>{let b=cs.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(o.emit("assistant:message",h),!Bo&&rt()!=="anchor-top"&&$e()&&($r+=1,G(),Ze())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&o.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&o.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):o.emit("approval:requested",{approval:h.approval,message:h}))}),cs.clear(),u.forEach((h,b)=>{cs.set(b,h)})},zf=(l,u,h)=>{var it,He,Pe,qe,Je,bt;let b=document.createElement("div"),W=(()=>{var Ne;let P=s.find(Be=>Be.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),z=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),F=new Set,B=new Set,se=s.some(P=>P.renderAskUserQuestion),ae=[],Z=[],ve=r.enableComponentStreaming!==!1,Fe=s.some(P=>P.renderApproval)&&r.approval!==!1,Se=[];if(u.forEach(P=>{var Xe,kt,rn,ar,Gn,No,Oo,gs,fs,Vt,Fo,go,fo,zr,_o,gr;F.add(P.id);let Ne=se&&Kr(P),Be=Fe&&P.variant==="approval"&&!!P.approval,fe=!Ne&&P.role==="assistant"&&!P.variant&&ve&&$i(P);if(!Be&&pr.has(P.id)){let et=l.querySelector(`#wrapper-${P.id}`);et==null||et.removeAttribute("data-preserve-runtime"),pr.delete(P.id)}if(!fe&&kr.has(P.id)){let et=l.querySelector(`#wrapper-${P.id}`);et==null||et.removeAttribute("data-preserve-runtime"),kr.delete(P.id)}let Ot=Kr(P)?`:${(Xe=P.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(kt=P.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=lg(P,ss)+Ot,zt=Ne||Be||fe?null:dg(Mr,P.id,Dt);if(zt){b.appendChild(zt.cloneNode(!0)),Kr(P)&&((rn=P.toolCall)!=null&&rn.id)&&((ar=P.agentMetadata)==null?void 0:ar.awaitingLocalTool)===!0&&!((Gn=P.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Cs(P,r,Y.composerOverlay));return}let wt=null,jt=s.find(et=>!!(P.variant==="reasoning"&&et.renderReasoning||P.variant==="tool"&&et.renderToolCall||!P.variant&&et.renderMessage)),Kn=(No=r.layout)==null?void 0:No.messages;if(Kr(P)&&((Oo=P.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){_r.delete(P.id);let et=l.querySelector(`#wrapper-${P.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(ra(P)&&((fs=(gs=r.features)==null?void 0:gs.suggestReplies)==null?void 0:fs.enabled)!==!1)return;if(Kr(P)&&((Fo=(Vt=r.features)==null?void 0:Vt.askUserQuestion)==null?void 0:Fo.enabled)!==!1){let et=s.find(cn=>typeof cn.renderAskUserQuestion=="function");if(et&&At.current){let cn=_r.get(P.id),_t=cn!==Dt,Ft=null;if(_t){let{payload:St,complete:xn}=Gr(P),En=P.id,Ir=()=>{var un;return(un=At.current)==null?void 0:un.getMessages().find(Mn=>Mn.id===En)};Ft=et.renderAskUserQuestion({message:P,payload:St,complete:xn,resolve:un=>{var kn;let Mn=Ir();Mn&&((kn=At.current)==null||kn.resolveAskUserQuestion(Mn,un))},dismiss:()=>{var Mn,kn,$o;let un=Ir();(Mn=un==null?void 0:un.agentMetadata)!=null&&Mn.awaitingLocalTool&&((kn=At.current)==null||kn.markAskUserQuestionResolved(un),($o=At.current)==null||$o.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let ft=cn!=null;if(_t&&Ft===null&&!ft){((go=P.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=P.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Cs(P,r,Y.composerOverlay));return}let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-${P.id}`,Kt.setAttribute("data-wrapper-id",P.id),Kt.setAttribute("data-ask-plugin-stub","true"),Kt.setAttribute("data-preserve-runtime","true"),b.appendChild(Kt),ae.push({messageId:P.id,fingerprint:Dt,bubble:Ft});return}else{((zr=P.agentMetadata)==null?void 0:zr.awaitingLocalTool)===!0&&!((_o=P.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(B.add(P.toolCall.id),Cs(P,r,Y.composerOverlay));return}}else if(Be){let et=s.find(ft=>typeof ft.renderApproval=="function"),_t=pr.get(P.id)!==Dt,Ft=null;if(_t&&(et!=null&&et.renderApproval)){let ft=P.id,Kt=(St,xn)=>{var Ir,un,Mn;let En=(Ir=At.current)==null?void 0:Ir.getMessages().find(kn=>kn.id===ft);En!=null&&En.approval&&(En.approval.toolType==="webmcp"?(un=At.current)==null||un.resolveWebMcpApproval(En.id,St):(Mn=At.current)==null||Mn.resolveApproval(En.approval,St,xn))};Ft=et.renderApproval({message:P,defaultRenderer:()=>Hi(P,r),config:r,approve:St=>Kt("approved",St),deny:St=>Kt("denied",St)})}if(_t&&Ft===null){let ft=l.querySelector(`#wrapper-${P.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),pr.delete(P.id),wt=Hi(P,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${P.id}`,ft.setAttribute("data-wrapper-id",P.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),b.appendChild(ft),Se.push({messageId:P.id,fingerprint:Dt,bubble:Ft});return}}else if(jt)if(P.variant==="reasoning"&&P.reasoning&&jt.renderReasoning){if(!Ue)return;wt=jt.renderReasoning({message:P,defaultRenderer:()=>Jl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&jt.renderToolCall){if(!Ae)return;wt=jt.renderToolCall({message:P,defaultRenderer:()=>Xl(P,r),config:r})}else jt.renderMessage&&(wt=jt.renderMessage({message:P,defaultRenderer:()=>{let et=Ws(P,h,Kn,r.messageActions,le,{loadingIndicatorRenderer:W,widgetConfig:r});return P.role!=="user"&&tc(et,P,r,_),et},config:r}));if(!wt&&fe){let et=ji(P);if(et){let cn=kr.get(P.id),_t=cn!==Dt,Ft=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(_t){let Kt=_i(et,{config:r,message:P,transform:h});if(Kt)if(Ft){let St=document.createElement("div");if(St.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(" "),St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let xn=document.createElement("div");xn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",xn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(xn)}St.appendChild(Kt),ft=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),St.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let xn=document.createElement("div");xn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",xn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(xn)}St.appendChild(Kt),ft=St}}if(ft||cn!=null){let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-${P.id}`,Kt.setAttribute("data-wrapper-id",P.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:P.id,fingerprint:Dt,bubble:ft});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ue)return;wt=Jl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;wt=Xl(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Hi(P,r)}else{let et=(gr=r.layout)==null?void 0:gr.messages;et!=null&&et.renderUserMessage&&P.role==="user"?wt=et.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):et!=null&&et.renderAssistantMessage&&P.role==="assistant"?wt=et.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Ws(P,h,et,r.messageActions,le,{loadingIndicatorRenderer:W,widgetConfig:r}),P.role!=="user"&&wt&&tc(wt,P,r,_)}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Yt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Yt.classList.add("persona-w-full"),Yt.appendChild(wt),pg(Mr,P.id,Dt,Yt),b.appendChild(Yt)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Be=Ne.getAttribute("data-persona-ask-sheet-for");Be&&!B.has(Be)&&xo(Y.composerOverlay,Be)}),(He=(it=r.features)==null?void 0:it.toolCallDisplay)!=null&&He.grouped){let P=[],Ne=[];u.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&Ae){Ne.push(Be);return}Ne.length>1&&P.push(Ne),Ne=[]}),Ne.length>1&&P.push(Ne),P.forEach((Be,fe)=>{var Xe,kt;let Ot=Be.map(rn=>Array.from(b.children).find(ar=>ar instanceof HTMLElement&&ar.getAttribute("data-wrapper-id")===rn.id)).filter(rn=>!!rn);if(Ot.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${fe}-${Be[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${fe}-${Be[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${Be.length} tools`,Kn=(kt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:kt.call(Xe,{messages:Be,toolCalls:Be.map(rn=>rn.toolCall).filter(rn=>!!rn),defaultSummary:jt,config:r});z(wt,Kn)||(wt.textContent=jt);let Yt=document.createElement("div");Yt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(wt,Yt),Dt.appendChild(zt),Ot[0].before(Dt),Ot.forEach((rn,ar)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),ar<Ot.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(rn),Yt.appendChild(Gn)})})}ug(Mr,F);let st=u.some(P=>P.role==="assistant"&&P.streaming),je=u[u.length-1],gt=(je==null?void 0:je.role)==="assistant"&&!je.streaming&&je.variant!=="approval";if(Er&&u.some(P=>P.role==="user")&&!st&&!gt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:es},Ne=s.find(fe=>fe.renderLoadingIndicator),Be=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(Be=Ne.renderLoadingIndicator(P)),Be===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(Be=r.loadingIndicator.render(P)),Be===null&&(Be=es()),Be){let fe=document.createElement("div"),Ot=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;fe.className=Ot?["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(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Be);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(fe),b.appendChild(Dt)}}if(!Er&&u.length>0){let P=u[u.length-1],Ne={config:r,lastMessage:P,messageCount:u.length},Be=s.find(Ot=>Ot.renderIdleIndicator),fe=null;if(Be!=null&&Be.renderIdleIndicator&&(fe=Be.renderIdleIndicator(Ne)),fe===null&&((Je=r.loadingIndicator)!=null&&Je.renderIdle)&&(fe=r.loadingIndicator.renderIdle(Ne)),fe){let Ot=document.createElement("div"),Dt=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Ot.className=Dt?["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(" "),Ot.setAttribute("data-idle-indicator","true"),Ot.appendChild(fe);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ot),b.appendChild(zt)}}if(fi(l,b),ae.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Be}of ae){let fe=l.querySelector(`#wrapper-${P}`);fe&&Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Ne),_r.set(P,Ne))}if(_r.size>0)for(let P of _r.keys())F.has(P)||_r.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Be}of Z){let fe=l.querySelector(`#wrapper-${P}`);fe&&Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Ne),kr.set(P,Ne))}if(kr.size>0)for(let P of kr.keys())F.has(P)||kr.delete(P);if(Se.length>0)for(let{messageId:P,fingerprint:Ne,bubble:Be}of Se){let fe=l.querySelector(`#wrapper-${P}`);fe&&Be!==null&&(fe.replaceChildren(Be),fe.setAttribute("data-bubble-fp",Ne),pr.set(P,Ne))}if(pr.size>0)for(let P of pr.keys())F.has(P)||pr.delete(P)},$s=(l,u,h)=>{zf(l,u,h),oo()},js=null,Vf=()=>{var h;if(js)return;let l=b=>{let T=b.composedPath();T.includes(Oe)||tt&&T.includes(tt)||$t(!1,"user")};js=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Cc=()=>{var u;if(!js)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("pointerdown",js,!0),js=null};dt.push(()=>Cc());let Us=null,Kf=()=>{var h;if(Us)return;let l=b=>{b.key==="Escape"&&(b.isComposing||$t(!1,"user"))};Us=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Sc=()=>{var u;if(!Us)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("keydown",Us,!0),Us=null};dt.push(()=>Sc());let qs=!1,Ac=new Set,Gf=()=>{var u,h,b,T;let l=(b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},ds=()=>{var gt,it,He,Pe;if(!D())return;let l=Y.peekBanner,u=Y.peekTextNode;if(!l||!u)return;if(L){l.classList.remove("persona-pill-peek--visible");return}let h=(gt=_==null?void 0:_.getMessages())!=null?gt:[],b;for(let qe=h.length-1;qe>=0;qe--){let Je=h[qe];if(Je.role==="assistant"&&Je.content){b=Je;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let T=b.content,W=!!b.streaming,z=Gf(),F=vi(z),B=F.type!=="none"?ha(F.type,z==null?void 0:z.plugins):null,se=((it=B==null?void 0:B.isAnimating)==null?void 0:it.call(B,b))===!0,ae=B!==null&&(W||se);ae&&B&&!Ac.has(B.name)&&(Nl(B,e),Ac.add(B.name));let Z=ae&&(B!=null&&B.containerClass)?B.containerClass:null,ve=(He=u.dataset.personaPeekStreamClass)!=null?He:null;ve&&ve!==Z&&(u.classList.remove(ve),delete u.dataset.personaPeekStreamClass),Z&&ve!==Z&&(u.classList.add(Z),u.dataset.personaPeekStreamClass=Z),ae?(u.style.setProperty("--persona-stream-step",`${F.speed}ms`),u.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Fe=ae?wi(T,F.buffer,B,b,W):T;if(ae&&F.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let qe=document.createElement("div"),Je=ba();Je.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Je),fi(u,qe)}else{let qe=Math.max(0,Fe.length-100),Je=Fe.length>100?Fe.slice(-100):Fe,bt=Rr(Je);if(!ae||!B){let P=Fe.length>100?`\u2026${Je}`:Je;u.textContent!==P&&(u.textContent=P)}else{let P=bt;(B.wrap==="char"||B.wrap==="word")&&(P=ya(bt,B.wrap,`peek-${b.id}`,{skipTags:B.skipTags,startIndex:qe}));let Ne=document.createElement("div");if(Ne.innerHTML=P,B.useCaret&&Je.length>0){let Be=Ci(),fe=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ot=fe[fe.length-1];Ot!=null&&Ot.parentNode?Ot.parentNode.insertBefore(Be,Ot.nextSibling):Ne.appendChild(Be)}fi(u,Ne),(Pe=B.onAfterRender)==null||Pe.call(B,{container:u,bubble:l,messageId:b.id,message:b,speed:F.speed,duration:F.duration})}}let je=Er||qs;l.classList.toggle("persona-pill-peek--visible",je)};if(D()){let l=Y.peekBanner;if(l){let b=T=>{T.preventDefault(),T.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",b),dt.push(()=>{l.removeEventListener("pointerdown",b)})}let u=()=>{qs||(qs=!0,ds())},h=()=>{qs&&(qs=!1,ds())};de.addEventListener("pointerenter",u),de.addEventListener("pointerleave",h),dt.push(()=>{de.removeEventListener("pointerenter",u),de.removeEventListener("pointerleave",h)}),tt&&(tt.addEventListener("pointerenter",u),tt.addEventListener("pointerleave",h),dt.push(()=>{tt.removeEventListener("pointerenter",u),tt.removeEventListener("pointerleave",h)}))}let Jf=l=>{var ve,Fe,Se,st,je,gt,it,He;let u=(Fe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Fe:{},h=(Se=u.expandedSize)!=null?Se:"anchored",b=(st=u.bottomOffset)!=null?st:"16px",T=u.collapsedMaxWidth,W=(je=u.expandedMaxWidth)!=null?je:"880px",z=(gt=u.expandedTopOffset)!=null?gt:"5vh",F=(it=u.modalMaxWidth)!=null?it:"880px",B=(He=u.modalMaxHeight)!=null?He:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="var(--persona-pill-area-height, 80px)",Z=Oe.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",tt){let Pe=tt.style;Pe.bottom=b,Pe.width=T!=null?T:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=F,Z.maxWidth=se,Z.maxHeight=B,Z.height=B;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${ae})`,Z.top=z,Z.width=W,Z.maxWidth=se}},zs=()=>{var B,se,ae,Z,ve,Fe,Se,st;if(!N())return;if(D()){let gt=(ae=((se=(B=r.launcher)==null?void 0:B.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",it=L?"expanded":"collapsed";Oe.dataset.state=it,Oe.dataset.expandedSize=gt,tt&&(tt.dataset.state=it,tt.dataset.expandedSize=gt),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Jf(L),pe.style.display=L?"flex":"none",be(),L?(Vf(),Kf()):(Cc(),Sc()),ds();return}let l=on(r),u=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Fe:640,b=(st=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?st:!0,T=u.innerWidth<=h,W=b&&T&&S,z=Xn(r).reveal;L?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Xt?Xt.element.style.display="none":ln&&(ln.style.display="none")):(l?l&&(z==="overlay"||z==="push")&&!W?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Xt?Xt.element.style.display=l?"none":"":ln&&(ln.style.display=l?"none":""))},$t=(l,u="user")=>{var W,z;if(!N()||L===l)return;let h=L;L=l,zs();let b=(()=>{var Se,st,je,gt,it,He,Pe,qe,Je,bt;let F=(st=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?st:!1,B=(je=e.ownerDocument.defaultView)!=null?je:window,se=(it=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?it:!0,ae=(Pe=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?Pe:640,Z=B.innerWidth<=ae,ve=on(r)&&se&&Z,Fe=D()&&((bt=(Je=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Je.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return F||se&&Z&&S||ve||Fe})();if(L&&b){if(!Qt){let F=e.getRootNode(),B=F instanceof ShadowRoot?F.host:e.closest(".persona-host");B&&(Qt=Ol(B,(z=(W=r.launcher)==null?void 0:W.zIndex)!=null?z:Cn))}an||(an=Fl(e.ownerDocument))}else L||(Qt==null||Qt(),Qt=null,an==null||an(),an=null);L&&(Vs(),rt()==="follow"?Hn(!0):po());let T={open:L,source:u,timestamp:Date.now()};L&&!h?o.emit("widget:opened",T):!L&&h&&o.emit("widget:closed",T),o.emit("widget:state",{open:L,launcherEnabled:S,voiceActive:ht.active,streaming:_.isStreaming()})},el=l=>{Rt(l?"stop":"send"),q&&(q.disabled=l),Wo.buttons.forEach(u=>{u.disabled=l}),Re.dataset.personaComposerStreaming=l?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},tl=()=>{ht.active||Te&&Te.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>tl(),200)});let Tc=()=>{var h,b,T,W,z,F,B,se,ae,Z,ve;xr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",yn.textContent=(W=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Te.placeholder=(F=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?F:"How can I help...";let l=Ce.querySelector("[data-persona-intro-card]");if(l){let Fe=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Ce.classList.remove("persona-gap-3"),Ce.classList.add("persona-gap-6")):(Ce.classList.remove("persona-gap-6"),Ce.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!(_!=null&&_.isStreaming())&&(ge.textContent=(ve=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?ve:"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 l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{g(u=>({...u,sessionId:l}))}});let Do=null,Qf=()=>{Do==null&&(Do=setInterval(()=>{let l=Ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Do),Do=null;return}let u=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Qa(u-b))})},100))};_=new Ms(r,{onMessagesChanged(l){var b;$s(Ve,l,Ie),Qf(),os(l),Hn(!Er),qf(l);let u=[...l].reverse().find(T=>T.role==="user");l.length===0&&fn(),!as||Bo?(as=!0,is=(b=u==null?void 0:u.id)!=null?b:null):u&&u.id!==is&&(is=u.id,Uf(u.id));let h=ht.lastUserMessageId;u&&u.id!==h&&(ht.lastUserMessageId=u.id,o.emit("user:message",u)),ht.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),co(l),ds()},onStatusChanged(l){var b;let u=(b=r.statusIndicator)!=null?b:{};Ye(sn,(T=>{var W,z,F,B;return T==="idle"?(W=u.idleText)!=null?W:wn.idle:T==="connecting"?(z=u.connectingText)!=null?z:wn.connecting:T==="connected"?(F=u.connectedText)!=null?F:wn.connected:T==="error"?(B=u.errorText)!=null?B:wn.error:wn[T]})(l),u,l)},onStreamingChanged(l){Er=l,el(l),_&&$s(Ve,_.getMessages(),Ie),l||Hn(!0),ds()},onVoiceStatusChanged(l){var u,h;if(o.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":qr(),us();break;case"processing":qr(),th();break;case"speaking":qr(),nh();break;default:l==="idle"&&_.isBargeInActive()?(qr(),us(),q==null||q.setAttribute("aria-label","End voice session")):(ht.active=!1,qr(),rr("system"),Wn());break}},onArtifactsState(l){Fn=l,jn(),co()}}),At.current=_;let nl=null;if(_.onReadAloudChange((l,u)=>{var T;no=l,ro=u,oo();let h=l!=null?l:nl;l&&(nl=l);let b=h&&(T=_.getMessages().find(W=>W.id===h))!=null?T:null;o.emit("message:read-aloud",{messageId:h,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(nl=null)}),as=!0,((Dd=(Bd=r.voiceRecognition)==null?void 0:Bd.provider)==null?void 0:Dd.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ce||r.onSSEEvent)&&_.setSSEEventCallback((l,u)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,u),oe==null||oe.processEvent(l,u),ce==null||ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),c&&c.then(l=>{var u,h,b;if(l){if(l.metadata&&(d=oc(l.metadata),M.syncFromMetadata()),(u=l.messages)!=null&&u.length){Bo=!0;try{_.hydrateMessages(l.messages)}finally{Bo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Ec=()=>{var u,h,b;!D()||L||!((b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||$t(!0,"auto")},Mc=l=>{var T;if(l.preventDefault(),_.isStreaming()){_.cancel(),oe==null||oe.reset(),J==null||J.update();return}let u=Te.value.trim(),h=(T=vt==null?void 0:vt.hasAttachments())!=null?T:!1;if(!u&&!h)return;Ec();let b;h&&(b=[],b.push(...vt.getContentParts()),u&&b.push(la(u))),Te.value="",Te.style.height="auto",Da(),_.sendMessage(u,{contentParts:b}),h&&vt.clearAttachments()},Xf=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},rl={...hi},ol=!1,Da=()=>{rl={...hi}},Yf=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var u;return(u=l.content)!=null?u:""}).filter(l=>l.length>0),Zf=l=>{if(!Te)return;ol=!0,Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),ol=!1;let u=Te.value.length;Te.setSelectionRange(u,u)},kc=()=>{ol||Da()},Lc=l=>{if(Te){if(Xf()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=Te.selectionStart===0&&Te.selectionEnd===0,h=ig({direction:l.key==="ArrowUp"?"up":"down",history:Yf(),currentValue:Te.value,atStart:u,state:rl});if(rl=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Zf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Da(),l.preventDefault(),ge.click()}}},Pc=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),oe==null||oe.reset(),J==null||J.update(),Da(),l.preventDefault(),l.stopImmediatePropagation())},Ic=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let u=Ub(l.clipboardData);u.length!==0&&(l.preventDefault(),await vt.handleFiles(u))},or=null,Pr=!1,ps=null,mt=null,Rc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Na=(l="user")=>{var W,z,F,B,se,ae,Z;if(Pr||_.isStreaming())return;let u=Rc();if(!u)return;or=new u;let b=(z=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?z:2e3;or.continuous=!0,or.interimResults=!0,or.lang="en-US";let T=Te.value;or.onresult=ve=>{let Fe="",Se="";for(let je=0;je<ve.results.length;je++){let gt=ve.results[je],it=gt[0].transcript;gt.isFinal?Fe+=it+" ":Se=it}let st=T+Fe+Se;Te.value=st,ps&&clearTimeout(ps),(Fe||Se)&&(ps=window.setTimeout(()=>{let je=Te.value.trim();je&&or&&Pr&&(uo(),Te.value="",Te.style.height="auto",_.sendMessage(je,{viaVoice:!0}))},b))},or.onerror=ve=>{ve.error!=="no-speech"&&uo()},or.onend=()=>{if(Pr){let ve=Te.value.trim();ve&&ve!==T.trim()&&(Te.value="",Te.style.height="auto",_.sendMessage(ve,{viaVoice:!0})),uo()}};try{if(or.start(),Pr=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),rr(l),Wn(),q){let ve=(F=r.voiceRecognition)!=null?F:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(B=ve.iconName)!=null?B:"mic",iconSize:parseFloat((Z=(ae=ve.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Fe=ve.recordingBackgroundColor,Se=ve.recordingIconColor,st=ve.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let je=q.querySelector("svg");je&&je.setAttribute("stroke",Se)}st&&(q.style.borderColor=st),q.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Pr){if(Pr=!1,ps&&(clearTimeout(ps),ps=null),or){try{or.stop()}catch{}or=null}if(ht.active=!1,rr(l),Wn(),q){if(q.classList.remove("persona-voice-recording"),mt){q.style.backgroundColor=mt.backgroundColor,q.style.color=mt.color,q.style.borderColor=mt.borderColor;let u=q.querySelector("svg");u&&u.setAttribute("stroke",mt.color||"currentColor"),mt=null}q.setAttribute("aria-label","Start voice recognition")}}},eh=(l,u)=>{var it,He,Pe,qe,Je,bt,P,Ne,Be;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((it=l==null?void 0:l.provider)==null?void 0:it.type)==="runtype",T=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(h||b||T))return null;let z=y("div","persona-send-button-wrapper"),F=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let B=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",se=(qe=u==null?void 0:u.size)!=null?qe:"40px",ae=(Je=l==null?void 0:l.iconSize)!=null?Je:se,Z=parseFloat(ae)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:u==null?void 0:u.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:u==null?void 0:u.textColor;F.style.width=ae,F.style.height=ae,F.style.minWidth=ae,F.style.minHeight=ae,F.style.fontSize="18px",F.style.lineHeight="1",Fe?F.style.color=Fe:F.style.color="var(--persona-text, #111827)";let st=xe(B,Z,Fe||"currentColor",1.5);st?F.appendChild(st):F.textContent="\u{1F3A4}",ve?F.style.backgroundColor=ve:F.style.backgroundColor="",l!=null&&l.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l!=null&&l.borderColor&&(F.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),z.appendChild(F);let je=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((Be=l==null?void 0:l.showTooltip)!=null?Be:!1)&&je){let fe=y("div","persona-send-button-tooltip");fe.textContent=je,z.appendChild(fe)}return{micButton:F,micButtonWrapper:z}},sl=()=>{var u,h,b,T,W;if(!q||mt)return;let l=(u=r.voiceRecognition)!=null?u:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},al=(l,u)=>{var W,z,F,B,se;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let b=(se=mt==null?void 0:mt.iconSize)!=null?se:parseFloat((B=(F=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?F:(z=r.sendButton)==null?void 0:z.size)!=null?B:"40")||24,T=xe(l,b,u,1.5);T&&q.appendChild(T)},Oa=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},us=()=>{var T;if(!q)return;sl();let l=(T=r.voiceRecognition)!=null?T:{},u=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(Oa(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=u!=null?u:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=q.querySelector("svg");W&&W.setAttribute("stroke",h)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},th=()=>{var F,B,se,ae,Z,ve,Fe,Se;if(!q)return;sl();let l=(F=r.voiceRecognition)!=null?F:{},u=_.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",b=(ae=(se=l.processingIconColor)!=null?se:mt==null?void 0:mt.color)!=null?ae:"",T=(ve=(Z=l.processingBackgroundColor)!=null?Z:mt==null?void 0:mt.backgroundColor)!=null?ve:"",W=(Se=(Fe=l.processingBorderColor)!=null?Fe:mt==null?void 0:mt.borderColor)!=null?Se:"";Oa(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=T,q.style.borderColor=W;let z=b||"currentColor";q.style.color=z,al(h,z),q.setAttribute("aria-label","Processing voice input"),u==="none"&&(q.style.cursor="default")},nh=()=>{var se,ae,Z,ve,Fe,Se,st,je,gt,it,He,Pe;if(!q)return;sl();let l=(se=r.voiceRecognition)!=null?se:{},u=_.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",b=(ae=l.speakingIconName)!=null?ae:h,T=(Se=l.speakingIconColor)!=null?Se:u==="barge-in"?(ve=(Z=l.recordingIconColor)!=null?Z:mt==null?void 0:mt.color)!=null?ve:"":(Fe=mt==null?void 0:mt.color)!=null?Fe:"",W=(gt=l.speakingBackgroundColor)!=null?gt:u==="barge-in"?(st=l.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(je=mt==null?void 0:mt.backgroundColor)!=null?je:"",z=(Pe=l.speakingBorderColor)!=null?Pe:u==="barge-in"?(it=l.recordingBorderColor)!=null?it:"":(He=mt==null?void 0:mt.borderColor)!=null?He:"";Oa(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=W,q.style.borderColor=z;let F=T||"currentColor";q.style.color=F,al(b,F);let B=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",B),u==="none"&&(q.style.cursor="default"),u==="barge-in"&&q.classList.add("persona-voice-recording")},qr=()=>{var l,u,h;q&&(Oa(),mt&&(q.style.backgroundColor=(l=mt.backgroundColor)!=null?l:"",q.style.color=(u=mt.color)!=null?u:"",q.style.borderColor=(h=mt.borderColor)!=null?h:"",al(mt.iconName,mt.color||"currentColor"),mt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},Fa=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Wn(),rr("user"),qr()});return}_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),ht.manuallyDeactivated=!_.isVoiceActive(),Wn(),rr("user"),_.isVoiceActive()?us():qr()});return}if(Pr){let h=Te.value.trim();ht.manuallyDeactivated=!0,Wn(),uo("user"),h&&(Te.value="",Te.style.height="auto",_.sendMessage(h))}else ht.manuallyDeactivated=!1,Wn(),Na("user")};Nn=Fa,q&&(q.addEventListener("click",Fa),dt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),qr()):uo("system"),q&&q.removeEventListener("click",Fa)}));let rh=o.on("assistant:complete",()=>{_s&&(ht.active||ht.manuallyDeactivated||_s==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!ht.active&&!ht.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),rr("auto"),_.isVoiceActive()&&us()}):Na("auto"))},600))});dt.push(rh);let oh=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(oh);let Wc=()=>{$t(!L,"user")},Xt=null,ln=null;if(S&&!D()){let{instance:l,element:u}=ql({config:r,plugins:s,onToggle:Wc});Xt=l,l||(ln=u)}Xt?e.appendChild(Xt.element):ln&&e.appendChild(ln),zs(),os(),Tc(),el(_.isStreaming()),rt()==="follow"?Hn(!0):po(),Ha(),O&&(!S||D()?setTimeout(()=>tl(),0):L&&setTimeout(()=>tl(),200));let Vs=()=>{var B,se,ae,Z,ve,Fe,Se,st,je,gt,it,He,Pe,qe,Je,bt,P,Ne,Be,fe,Ot,Dt;if(D()){In(),zs();return}let l=on(r),u=(se=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?se:!1,h=l||u||((Z=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Z:!1),b=(ve=e.ownerDocument.defaultView)!=null?ve:window,T=(Se=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Se:!0,W=(je=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?je:640,z=b.innerWidth<=W,F=T&&z&&S;try{if(F){be(),So(e,r);return}if(H&&(H=!1,be(),So(e,r)),!S&&!l){de.style.height="",de.style.width="";return}if(!u&&!l){let zt=(it=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?it:r==null?void 0:r.launcherWidth,wt=zt!=null?zt:Qn;de.style.width=wt,de.style.maxWidth=wt}if(Sr(),!h){let zt=b.innerHeight,wt=64,jt=(Pe=(He=r.launcher)==null?void 0:He.heightOffset)!=null?Pe:0,Kn=Math.max(200,zt-wt),Yt=Math.min(640,Kn),Xe=Math.max(200,Yt-jt);de.style.height=`${Xe}px`}}finally{if(In(),zs(),L&&S){let wt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((bt=(Je=r.launcher)==null?void 0:Je.mobileBreakpoint)!=null?bt:640),jt=(Ne=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Ne:!1,Kn=(fe=(Be=r.launcher)==null?void 0:Be.mobileFullscreen)!=null?fe:!0,Yt=on(r)&&Kn&&wt,Xe=jt||Kn&&wt&&S||Yt;if(Xe&&!an){let kt=e.getRootNode(),rn=kt instanceof ShadowRoot?kt.host:e.closest(".persona-host");rn&&!Qt&&(Qt=Ol(rn,(Dt=(Ot=r.launcher)==null?void 0:Ot.zIndex)!=null?Dt:Cn)),an=Fl(e.ownerDocument)}else Xe||(Qt==null||Qt(),Qt=null,an==null||an(),an=null)}}};Vs();let Hc=(Nd=e.ownerDocument.defaultView)!=null?Nd:window;if(Hc.addEventListener("resize",Vs),dt.push(()=>Hc.removeEventListener("resize",Vs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{In()});l.observe(Re),dt.push(()=>l.disconnect())}qn=Ce.scrollTop;let Bc=Xr(Ce),sh=()=>{let l=Ce.getRootNode(),u=typeof l.getSelection=="function"?l.getSelection():null;return u!=null?u:Ce.ownerDocument.getSelection()},il=()=>mg(sh(),Ce),Dc=()=>{let l=Ce.scrollTop,u=Xr(Ce),h=u<Bc;if(Bc=u,rt()!=="follow"){qn=l,Ze();return}let{action:b,nextLastScrollTop:T}=bi({following:Un.isFollowing(),currentScrollTop:l,lastScrollTop:qn,nearBottom:Yo(Ce,ls),userScrollThreshold:Ra,isAutoScrolling:mr||Ho||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qn=T,b==="resume"){il()||jr();return}b==="pause"&&Mt()};if(Ce.addEventListener("scroll",Dc,{passive:!0}),dt.push(()=>Ce.removeEventListener("scroll",Dc)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Vn()});l.observe(Ve),l.observe(Ce),dt.push(()=>l.disconnect())}let Nc=()=>{rt()==="follow"&&Un.isFollowing()&&il()&&Mt()},Oc=Ce.ownerDocument;Oc.addEventListener("selectionchange",Nc),dt.push(()=>{Oc.removeEventListener("selectionchange",Nc)});let Fc=l=>{if(rt()!=="follow")return;let u=xi({following:Un.isFollowing(),deltaY:l.deltaY,nearBottom:Yo(Ce,ls),resumeWhenNearBottom:!0});u==="pause"?Mt():u==="resume"&&!il()&&jr()};Ce.addEventListener("wheel",Fc,{passive:!0}),dt.push(()=>Ce.removeEventListener("wheel",Fc)),ct.addEventListener("click",()=>{fn(),Ce.scrollTop=Ce.scrollHeight,qn=Ce.scrollTop,jr(),Hn(!0),Ze()}),dt.push(()=>ct.remove()),dt.push(()=>{$(),fn()});let _c=()=>{Ke&&(Tr&&(Ke.removeEventListener("click",Tr),Tr=null),N()?(Ke.style.display="",Tr=()=>{$t(!1,"user")},Ke.addEventListener("click",Tr)):Ke.style.display="none")};_c(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Mr.clear(),jr(),xo(Y.composerOverlay);try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),ce==null||ce.clear(),oe==null||oe.reset(),J==null||J.update()})})(),It&&It.addEventListener("submit",Mc),Te==null||Te.addEventListener("keydown",Lc),Te==null||Te.addEventListener("input",kc),Te==null||Te.addEventListener("paste",Ic);let $c=(Od=e.ownerDocument)!=null?Od:document;$c.addEventListener("keydown",Pc,!0);let jc="persona-attachment-drop-active",Ks=0,ll=()=>{Ks=0,pe.classList.remove(jc)},ms=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&vt!==null},Uc=l=>{!zi(l.dataTransfer)||!ms()||(Ks++,Ks===1&&pe.classList.add(jc))},qc=l=>{!zi(l.dataTransfer)||!ms()||(Ks--,Ks<=0&&ll())},zc=l=>{!zi(l.dataTransfer)||!ms()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Vc=l=>{var h;if(!zi(l.dataTransfer)||!ms())return;l.preventDefault(),l.stopPropagation(),ll();let u=Array.from((h=l.dataTransfer.files)!=null?h:[]);u.length!==0&&vt.handleFiles(u)},mo=!0;pe.addEventListener("dragenter",Uc,mo),pe.addEventListener("dragleave",qc,mo),e.addEventListener("dragover",zc,mo),e.addEventListener("drop",Vc,mo);let _a=e.ownerDocument,Kc=l=>{ms()&&l.preventDefault()},Gc=l=>{ms()&&l.preventDefault()};_a.addEventListener("dragover",Kc),_a.addEventListener("drop",Gc),dt.push(()=>{It&&It.removeEventListener("submit",Mc),Te==null||Te.removeEventListener("keydown",Lc),Te==null||Te.removeEventListener("input",kc),Te==null||Te.removeEventListener("paste",Ic),$c.removeEventListener("keydown",Pc,!0)}),dt.push(()=>{pe.removeEventListener("dragenter",Uc,mo),pe.removeEventListener("dragleave",qc,mo),e.removeEventListener("dragover",zc,mo),e.removeEventListener("drop",Vc,mo),_a.removeEventListener("dragover",Kc),_a.removeEventListener("drop",Gc),ll()}),dt.push(()=>{_.cancel()}),Xt?dt.push(()=>{Xt==null||Xt.destroy()}):ln&&dt.push(()=>{ln==null||ln.remove()});let nn={update(l){var xn,En,Ir,un,Mn,kn,$o,Gs,zd,Vd,Kd,Gd,Jd,Qd,Xd,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,Sp,Ap,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Su,Au,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu;let u=r.toolCall,h=r.messageActions,b=(xn=r.layout)==null?void 0:xn.messages,T=r.colorScheme,W=r.loadingIndicator,z=r.iterationDisplay,F=(En=r.features)==null?void 0:En.showReasoning,B=(Ir=r.features)==null?void 0:Ir.showToolCalls,se=(un=r.features)==null?void 0:un.toolCallDisplay,ae=(Mn=r.features)==null?void 0:Mn.reasoningDisplay;r={...r,...l},be(),So(e,r),Di(e,r),Ni(e,r),jn(),r.colorScheme!==T&&Fs();let Z=Ea.getForInstance(r.plugins);s.length=0,s.push(...Z),S=($o=(kn=r.launcher)==null?void 0:kn.enabled)!=null?$o:!0,R=(zd=(Gs=r.launcher)==null?void 0:Gs.autoExpand)!=null?zd:!1,Ue=(Kd=(Vd=r.features)==null?void 0:Vd.showReasoning)!=null?Kd:!0,Ae=(Jd=(Gd=r.features)==null?void 0:Gd.showToolCalls)!=null?Jd:!0,_e=(Xd=(Qd=r.features)==null?void 0:Qd.scrollToBottom)!=null?Xd:{};let ve=rt();ye=(Zd=(Yd=r.features)==null?void 0:Yd.scrollBehavior)!=null?Zd:{},ve!==rt()&&(fn(),jr()),vr(),Ze();let Fe=Le;if(Le=(tp=(ep=r.features)==null?void 0:ep.showEventStreamToggle)!=null?tp:!1,Le&&!Fe){if(ce||(X=new Aa(ie),ce=new Sa(re,X),oe=oe!=null?oe:new Ta,X.open().then(()=>ce==null?void 0:ce.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Tt)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,ee,Tt),oe==null||oe.processEvent(ee,Tt),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&Ee){let ee=(rp=(np=r.features)==null?void 0:np.eventStream)==null?void 0:rp.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"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=y("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Ut=xe("activity","18px","currentColor",1.5);Ut&&yt.appendChild(Ut);let lt=Y.clearChatButtonWrapper,Lt=Y.closeButtonWrapper,dn=lt||Lt;dn&&dn.parentNode===Ee?Ee.insertBefore(yt,dn):Ee.appendChild(yt),yt.addEventListener("click",()=>{te?dr():Br()})}}else!Le&&Fe&&(dr(),yt&&(yt.remove(),yt=null),ce==null||ce.clear(),X==null||X.destroy(),ce=null,X=null,oe==null||oe.reset(),oe=null);if(((op=r.launcher)==null?void 0:op.enabled)===!1&&Xt&&(Xt.destroy(),Xt=null),((sp=r.launcher)==null?void 0:sp.enabled)===!1&&ln&&(ln.remove(),ln=null),((ap=r.launcher)==null?void 0:ap.enabled)!==!1&&!Xt&&!ln){let{instance:ee,element:Tt}=ql({config:r,plugins:s,onToggle:Wc});Xt=ee,ee||(ln=Tt),e.appendChild(Tt)}Xt&&Xt.update(r),me&&((ip=r.launcher)==null?void 0:ip.title)!==void 0&&(me.textContent=r.launcher.title),ke&&((lp=r.launcher)==null?void 0:lp.subtitle)!==void 0&&(ke.textContent=r.launcher.subtitle);let Se=(cp=r.layout)==null?void 0:cp.header;if((Se==null?void 0:Se.layout)!==A&&Ee){let ee=Se?Is(r,Se,{showClose:N(),onClose:()=>$t(!1,"user")}):Yr({config:r,showClose:N(),onClose:()=>$t(!1,"user")});Ge.replaceHeader(ee),Ee=Ge.header.element,E=Ge.header.iconHolder,me=Ge.header.headerTitle,ke=Ge.header.headerSubtitle,Ke=Ge.header.closeButton,A=Se==null?void 0:Se.layout}else if(Se&&(E&&(E.style.display=Se.showIcon===!1?"none":""),me&&(me.style.display=Se.showTitle===!1?"none":""),ke&&(ke.style.display=Se.showSubtitle===!1?"none":""),Ke&&(Ke.style.display=Se.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let ee=Se.showClearChat;if(ee!==void 0){Y.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=Y;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let je=((dp=r.layout)==null?void 0:dp.showHeader)!==!1;Ee&&(Ee.style.display=je?"":"none");let gt=((pp=r.layout)==null?void 0:pp.showFooter)!==!1;Re&&(Re.style.display=gt?"":"none"),In(),Ze(),S!==I?S?$t(R,"auto"):(L=!0,zs()):R!==k&&$t(R,"auto"),k=R,I=S,Vs(),_c();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(u),qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),Je=JSON.stringify((up=r.layout)==null?void 0:up.messages)!==JSON.stringify(b),bt=((mp=r.loadingIndicator)==null?void 0:mp.render)!==(W==null?void 0:W.render)||((gp=r.loadingIndicator)==null?void 0:gp.renderIdle)!==(W==null?void 0:W.renderIdle)||((fp=r.loadingIndicator)==null?void 0:fp.showBubble)!==(W==null?void 0:W.showBubble),P=r.iterationDisplay!==z,Ne=((yp=(hp=r.features)==null?void 0:hp.showReasoning)!=null?yp:!0)!==(F!=null?F:!0)||((xp=(bp=r.features)==null?void 0:bp.showToolCalls)!=null?xp:!0)!==(B!=null?B:!0)||JSON.stringify((vp=r.features)==null?void 0:vp.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((wp=r.features)==null?void 0:wp.reasoningDisplay)!==JSON.stringify(ae);(Pe||qe||Je||bt||P||Ne)&&_&&(ss++,$s(Ve,_.getMessages(),Ie));let fe=(Cp=r.launcher)!=null?Cp:{},Ot=(Sp=fe.headerIconHidden)!=null?Sp:!1,Dt=(Tp=(Ap=r.layout)==null?void 0:Ap.header)==null?void 0:Tp.showIcon,zt=Ot||Dt===!1,wt=fe.headerIconName,jt=(Ep=fe.headerIconSize)!=null?Ep:"48px";if(E){let ee=pe.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(zt)E.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(E.style.display="",E.style.height=jt,E.style.width=jt,ee&&Tt&&(ee.contains(E)?E.nextSibling!==Tt&&(E.remove(),ee.insertBefore(E,Tt)):ee.insertBefore(E,Tt)),wt){let lt=parseFloat(jt)||24,Lt=xe(wt,lt*.6,"currentColor",1);Lt?E.replaceChildren(Lt):E.textContent=(Mp=fe.agentIconText)!=null?Mp:"\u{1F4AC}"}else if(fe.iconUrl){let lt=E.querySelector("img");if(lt)lt.src=fe.iconUrl,lt.style.height=jt,lt.style.width=jt;else{let Lt=document.createElement("img");Lt.src=fe.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=jt,Lt.style.width=jt,E.replaceChildren(Lt)}}else{let lt=E.querySelector("svg"),Lt=E.querySelector("img");(lt||Lt)&&E.replaceChildren(),E.textContent=(kp=fe.agentIconText)!=null?kp:"\u{1F4AC}"}let Ut=E.querySelector("img");Ut&&(Ut.style.height=jt,Ut.style.width=jt)}}let Kn=(Pp=(Lp=r.layout)==null?void 0:Lp.header)==null?void 0:Pp.showTitle,Yt=(Rp=(Ip=r.layout)==null?void 0:Ip.header)==null?void 0:Rp.showSubtitle;if(me&&(me.style.display=Kn===!1?"none":""),ke&&(ke.style.display=Yt===!1?"none":""),Ke){((Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showCloseButton)===!1?Ke.style.display="none":Ke.style.display="";let Tt=(Bp=fe.closeButtonSize)!=null?Bp:"32px",Ut=(Dp=fe.closeButtonPlacement)!=null?Dp:"inline";Ke.style.height=Tt,Ke.style.width=Tt;let{closeButtonWrapper:lt}=Y,Lt=Ut==="top-right",dn=lt==null?void 0:lt.classList.contains("persona-absolute");if(lt&&Lt!==dn)if(lt.remove(),Lt)lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(lt);else{let pt=(Op=(Np=fe.clearChat)==null?void 0:Np.placement)!=null?Op:"inline",pn=(_p=(Fp=fe.clearChat)==null?void 0:Fp.enabled)!=null?_p:!0;lt.className=pn&&pt==="inline"?"":"persona-ml-auto";let Dn=pe.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(lt)}if(Ke.style.color=fe.closeButtonColor||Pn.actionIconColor,fe.closeButtonBackgroundColor?(Ke.style.backgroundColor=fe.closeButtonBackgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let pt=fe.closeButtonBorderWidth||"0px",pn=fe.closeButtonBorderColor||"transparent";Ke.style.border=`${pt} solid ${pn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");fe.closeButtonBorderRadius?(Ke.style.borderRadius=fe.closeButtonBorderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(Ke.style.paddingLeft=fe.closeButtonPaddingX,Ke.style.paddingRight=fe.closeButtonPaddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),fe.closeButtonPaddingY?(Ke.style.paddingTop=fe.closeButtonPaddingY,Ke.style.paddingBottom=fe.closeButtonPaddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let vn=($p=fe.closeButtonIconName)!=null?$p:"x",fr=(jp=fe.closeButtonIconText)!=null?jp:"\xD7";Ke.innerHTML="";let Ln=xe(vn,"28px","currentColor",1);Ln?Ke.appendChild(Ln):Ke.textContent=fr;let Jt=(Up=fe.closeButtonTooltipText)!=null?Up:"Close chat",Jn=(qp=fe.closeButtonShowTooltip)!=null?qp:!0;if(Ke.setAttribute("aria-label",Jt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Jn&&Jt)){let pt=null,pn=()=>{if(pt||!Ke)return;let jo=Ke.ownerDocument,Js=jo.body;if(!Js)return;pt=Wr(jo,"div","persona-clear-chat-tooltip"),pt.textContent=Jt;let Qs=Wr(jo,"div");Qs.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Qs);let Uo=Ke.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Ao),pt.style.left=`${Uo.left+Uo.width/2}px`,pt.style.top=`${Uo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Js.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",pn),lt.addEventListener("mouseleave",Dn),Ke.addEventListener("focus",pn),Ke.addEventListener("blur",Dn),lt._cleanupTooltip=()=>{Dn(),lt&&(lt.removeEventListener("mouseenter",pn),lt.removeEventListener("mouseleave",Dn)),Ke&&(Ke.removeEventListener("focus",pn),Ke.removeEventListener("blur",Dn))}}}let{clearChatButton:Xe,clearChatButtonWrapper:kt}=Y;if(Xe){let ee=(zp=fe.clearChat)!=null?zp:{},Tt=(Vp=ee.enabled)!=null?Vp:!0,Ut=(Gp=(Kp=r.layout)==null?void 0:Kp.header)==null?void 0:Gp.showClearChat,lt=Ut!==void 0?Ut:Tt,Lt=(Jp=ee.placement)!=null?Jp:"inline";if(kt){kt.style.display=lt?"":"none";let{closeButtonWrapper:dn}=Y;!D()&&dn&&!dn.classList.contains("persona-absolute")&&(lt?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let vn=Lt==="top-right",fr=kt.classList.contains("persona-absolute");if(!D()&&vn!==fr&<){if(kt.remove(),vn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",pe.style.position="relative",pe.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let Jt=pe.querySelector(".persona-border-b-persona-divider"),Jn=Y.closeButtonWrapper;Jt&&Jn&&Jn.parentElement===Jt?Jt.insertBefore(kt,Jn):Jt&&Jt.appendChild(kt)}let Ln=Y.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(lt){if(!D()){let pt=(Qp=ee.size)!=null?Qp:"32px";Xe.style.height=pt,Xe.style.width=pt}let dn=(Xp=ee.iconName)!=null?Xp:"refresh-cw",vn=(Yp=ee.iconColor)!=null?Yp:"";Xe.style.color=vn||Pn.actionIconColor,Xe.innerHTML="";let fr=D()?"14px":"20px",Ln=xe(dn,fr,"currentColor",2);if(Ln&&Xe.appendChild(Ln),ee.backgroundColor?(Xe.style.backgroundColor=ee.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let pt=ee.borderWidth||"0px",pn=ee.borderColor||"transparent";Xe.style.border=`${pt} solid ${pn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");ee.borderRadius?(Xe.style.borderRadius=ee.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),ee.paddingX?(Xe.style.paddingLeft=ee.paddingX,Xe.style.paddingRight=ee.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),ee.paddingY?(Xe.style.paddingTop=ee.paddingY,Xe.style.paddingBottom=ee.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Jt=(Zp=ee.tooltipText)!=null?Zp:"Clear chat",Jn=(eu=ee.showTooltip)!=null?eu:!0;if(Xe.setAttribute("aria-label",Jt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Jn&&Jt)){let pt=null,pn=()=>{if(pt||!Xe)return;let jo=Xe.ownerDocument,Js=jo.body;if(!Js)return;pt=Wr(jo,"div","persona-clear-chat-tooltip"),pt.textContent=Jt;let Qs=Wr(jo,"div");Qs.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Qs);let Uo=Xe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Ao),pt.style.left=`${Uo.left+Uo.width/2}px`,pt.style.top=`${Uo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Js.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};kt.addEventListener("mouseenter",pn),kt.addEventListener("mouseleave",Dn),Xe.addEventListener("focus",pn),Xe.addEventListener("blur",Dn),kt._cleanupTooltip=()=>{Dn(),kt&&(kt.removeEventListener("mouseenter",pn),kt.removeEventListener("mouseleave",Dn)),Xe&&(Xe.removeEventListener("focus",pn),Xe.removeEventListener("blur",Dn))}}}}let rn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ma],ar=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];M=ka({parsers:rn,handlers:ar,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ie=nf(r,M,ne),_.updateConfig(r),$s(Ve,_.getMessages(),Ie),os(),Tc(),el(_.isStreaming());let Gn=((tu=r.voiceRecognition)==null?void 0:tu.enabled)===!0,No=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Oo=((ru=(nu=r.voiceRecognition)==null?void 0:nu.provider)==null?void 0:ru.type)==="runtype";if(Gn&&(No||Oo))if(!q||!at){let ee=eh(r.voiceRecognition,r.sendButton);ee&&(q=ee.micButton,at=ee.micButtonWrapper,ut.insertBefore(at,hn),q.addEventListener("click",Fa),q.disabled=_.isStreaming())}else{let ee=(ou=r.voiceRecognition)!=null?ou:{},Tt=(su=r.sendButton)!=null?su:{},Ut=(au=ee.iconName)!=null?au:"mic",lt=(iu=Tt.size)!=null?iu:"40px",Lt=(lu=ee.iconSize)!=null?lu:lt,dn=parseFloat(Lt)||24;q.style.width=Lt,q.style.height=Lt,q.style.minWidth=Lt,q.style.minHeight=Lt;let vn=(du=(cu=ee.iconColor)!=null?cu:Tt.textColor)!=null?du:"currentColor";q.innerHTML="";let fr=xe(Ut,dn,vn,2);fr?q.appendChild(fr):q.textContent="\u{1F3A4}";let Ln=(pu=ee.backgroundColor)!=null?pu:Tt.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn:q.style.color="var(--persona-text, #111827)",ee.borderWidth?(q.style.borderWidth=ee.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),ee.borderColor?q.style.borderColor=ee.borderColor:q.style.borderColor="",ee.paddingX?(q.style.paddingLeft=ee.paddingX,q.style.paddingRight=ee.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),ee.paddingY?(q.style.paddingTop=ee.paddingY,q.style.paddingBottom=ee.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Jt=at==null?void 0:at.querySelector(".persona-send-button-tooltip"),Jn=(uu=ee.tooltipText)!=null?uu:"Start voice recognition";if(((mu=ee.showTooltip)!=null?mu:!1)&&Jn)if(Jt)Jt.textContent=Jn,Jt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=Jn,at==null||at.insertBefore(pn,q)}else Jt&&(Jt.style.display="none");at.style.display="",q.disabled=_.isStreaming()}else q&&at&&(at.style.display="none",((fu=(gu=r.voiceRecognition)==null?void 0:gu.provider)==null?void 0:fu.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Pr&&uo());if(((hu=r.attachments)==null?void 0:hu.enabled)===!0)if(!ue||!K){let ee=(yu=r.attachments)!=null?yu:{},Ut=(xu=((bu=r.sendButton)!=null?bu:{}).size)!=null?xu:"40px";xt||(xt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xt.style.display="none",It.insertBefore(xt,Te)),Me||(Me=document.createElement("input"),Me.type="file",Me.accept=((vu=ee.allowedTypes)!=null?vu:Qr).join(","),Me.multiple=((wu=ee.maxFiles)!=null?wu:4)>1,Me.style.display="none",Me.setAttribute("aria-label","Attach files"),It.insertBefore(Me,Te)),ue=y("div","persona-send-button-wrapper"),K=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),K.type="button",K.setAttribute("aria-label",(Cu=ee.buttonTooltipText)!=null?Cu:"Attach file");let lt=(Su=ee.buttonIconName)!=null?Su:"paperclip",Lt=Ut,dn=parseFloat(Lt)||40,vn=Math.round(dn*.6);K.style.width=Lt,K.style.height=Lt,K.style.minWidth=Lt,K.style.minHeight=Lt,K.style.fontSize="18px",K.style.lineHeight="1",K.style.backgroundColor="transparent",K.style.color="var(--persona-primary, #111827)",K.style.border="none",K.style.borderRadius="6px",K.style.transition="background-color 0.15s ease",K.addEventListener("mouseenter",()=>{K.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),K.addEventListener("mouseleave",()=>{K.style.backgroundColor="transparent"});let fr=xe(lt,vn,"currentColor",1.5);fr?K.appendChild(fr):K.textContent="\u{1F4CE}",K.addEventListener("click",Jn=>{Jn.preventDefault(),Me==null||Me.click()}),ue.appendChild(K);let Ln=(Au=ee.buttonTooltipText)!=null?Au:"Attach file",Jt=y("div","persona-send-button-tooltip");Jt.textContent=Ln,ue.appendChild(Jt),Qe.append(ue),!vt&&Me&&xt&&(vt=Xo.fromConfig(ee),vt.setPreviewsContainer(xt),Me.addEventListener("change",async()=>{vt&&(Me!=null&&Me.files)&&(await vt.handleFileSelect(Me.files),Me.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(rf(ee.dropOverlay))}else{ue.style.display="";let ee=(Tu=r.attachments)!=null?Tu:{};Me&&(Me.accept=((Eu=ee.allowedTypes)!=null?Eu:Qr).join(","),Me.multiple=((Mu=ee.maxFiles)!=null?Mu:4)>1),vt&&vt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ue&&(ue.style.display="none"),vt&&vt.clearAttachments(),(ku=pe.querySelector(".persona-attachment-drop-overlay"))==null||ku.remove();let Vt=(Lu=r.sendButton)!=null?Lu:{},Fo=(Pu=Vt.useIcon)!=null?Pu:!1,go=(Iu=Vt.iconText)!=null?Iu:"\u2191",fo=Vt.iconName,zr=(Ru=Vt.tooltipText)!=null?Ru:"Send message",_o=(Wu=Vt.showTooltip)!=null?Wu:!1,gr=(Hu=Vt.size)!=null?Hu:"40px",et=Vt.backgroundColor,cn=Vt.textColor;if(Fo){if(ge.style.width=gr,ge.style.height=gr,ge.style.minWidth=gr,ge.style.minHeight=gr,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.innerHTML="",cn?ge.style.color=cn:ge.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let ee=parseFloat(gr)||24,Tt=(cn==null?void 0:cn.trim())||"currentColor",Ut=xe(fo,ee,Tt,2);Ut?ge.appendChild(Ut):ge.textContent=go}else ge.textContent=go;ge.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",et?(ge.style.backgroundColor=et,ge.classList.remove("persona-bg-persona-primary")):(ge.style.backgroundColor="",ge.classList.add("persona-bg-persona-primary"))}else ge.textContent=(Du=(Bu=r.copy)==null?void 0:Bu.sendButtonLabel)!=null?Du:"Send",ge.style.width="",ge.style.height="",ge.style.minWidth="",ge.style.minHeight="",ge.style.fontSize="",ge.style.lineHeight="",ge.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",et?(ge.style.backgroundColor=et,ge.classList.remove("persona-bg-persona-accent")):ge.classList.add("persona-bg-persona-accent"),cn?ge.style.color=cn:ge.classList.add("persona-text-white");Vt.borderWidth?(ge.style.borderWidth=Vt.borderWidth,ge.style.borderStyle="solid"):(ge.style.borderWidth="",ge.style.borderStyle=""),Vt.borderColor?ge.style.borderColor=Vt.borderColor:ge.style.borderColor="",Vt.paddingX?(ge.style.paddingLeft=Vt.paddingX,ge.style.paddingRight=Vt.paddingX):(ge.style.paddingLeft="",ge.style.paddingRight=""),Vt.paddingY?(ge.style.paddingTop=Vt.paddingY,ge.style.paddingBottom=Vt.paddingY):(ge.style.paddingTop="",ge.style.paddingBottom="");let _t=hn==null?void 0:hn.querySelector(".persona-send-button-tooltip");if(_o&&zr)if(_t)_t.textContent=zr,_t.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=zr,hn==null||hn.insertBefore(ee,ge)}else _t&&(_t.style.display="none");let Ft=($u=(Nu=r.layout)==null?void 0:Nu.contentMaxWidth)!=null?$u:D()?(_u=(Fu=(Ou=r.launcher)==null?void 0:Ou.composerBar)==null?void 0:Fu.contentMaxWidth)!=null?_u:"720px":void 0;Ft?(Ve.style.maxWidth=Ft,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",It&&(It.style.maxWidth=Ft,It.style.marginLeft="auto",It.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Ft,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let ft=(ju=r.statusIndicator)!=null?ju:{},Kt=(Uu=ft.visible)!=null?Uu:!0;if(sn.style.display=Kt?"":"none",_){let ee=_.getStatus();Ye(sn,(Ut=>{var lt,Lt,dn,vn;return Ut==="idle"?(lt=ft.idleText)!=null?lt:wn.idle:Ut==="connecting"?(Lt=ft.connectingText)!=null?Lt:wn.connecting:Ut==="connected"?(dn=ft.connectedText)!=null?dn:wn.connected:Ut==="error"?(vn=ft.errorText)!=null?vn:wn.error:wn[Ut]})(ee),ft,ee)}sn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";sn.classList.add(St)},open(){N()&&$t(!0,"api")},close(){N()&&$t(!1,"api")},toggle(){N()&&$t(!L,"api")},clearChat(){An=!1,_.clearMessages(),Mr.clear(),jr();try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}d={},M.syncFromMetadata(),ce==null||ce.clear(),oe==null||oe.reset(),J==null||J.update()},setMessage(l){return!Te||_.isStreaming()?!1:(!L&&N()&&$t(!0,"system"),Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let u=(l==null?void 0:l.trim())||Te.value.trim();return u?(!L&&N()&&$t(!0,"system"),Te.value="",Te.style.height="auto",_.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return _.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!L&&N()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Wn(),_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),rr("user"),_.isVoiceActive()&&us()})),!0):Pr?!0:Rc()?(!L&&N()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Wn(),Na("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Wn(),rr("user"),qr()}),!0):!1:Pr?(ht.manuallyDeactivated=!0,Wn(),uo("user"),!0):!1},injectMessage(l){return!L&&N()&&$t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!L&&N()&&$t(!0,"system");let u=_.injectAssistantMessage(l);return U&&(U=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),u},injectUserMessage(l){return!L&&N()&&$t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!L&&N()&&$t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!L&&N()&&$t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!L&&N()&&$t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!L&&N()&&$t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,u){return _.connectStream(l,u)},__pushEventStreamEvent(l){ce&&(oe==null||oe.processEvent(l.type,l.payload),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Le||!ce||Br()},hideEventStream(){te&&dr()},isEventStreamVisible(){return te},showArtifacts(){cr(r)&&(An=!1,jn(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){cr(r)&&(An=!0,jn())},upsertArtifact(l){return cr(r)?(An=!1,_.upsertArtifact(l)):null},selectArtifact(l){cr(r)&&_.selectArtifact(l)},clearArtifacts(){cr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return S&&!L&&!D()||!Te?!1:(Te.focus(),!0)},async resolveApproval(l,u,h){let T=_.getMessages().find(W=>{var z;return W.variant==="approval"&&((z=W.approval)==null?void 0:z.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){_.resolveWebMcpApproval(T.id,u);return}return _.resolveApproval(T.approval,u,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){g(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return N()&&L},isVoiceActive(){return ht.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:N()&&L,launcherEnabled:S,voiceActive:ht.active,streaming:_.isStreaming()}},showCSATFeedback(l){!L&&N()&&$t(!0,"system");let u=Ve.querySelector(".persona-feedback-container");u&&u.remove();let h=Ui({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!L&&N()&&$t(!0,"system");let u=Ve.querySelector(".persona-feedback-container");u&&u.remove();let h=qi({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return _.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return _.submitNPSFeedback(l,u)},destroy(){Do!=null&&(clearInterval(Do),Do=null),dt.forEach(l=>l()),Oe.remove(),tt==null||tt.remove(),Xt==null||Xt.destroy(),ln==null||ln.remove(),Tr&&Ke.removeEventListener("click",Tr)}};if((((Fd=n==null?void 0:n.debugTools)!=null?Fd:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={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=u,dt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",u),dt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Le){let F=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&nn.showEventStream()},B=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",B),dt.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",B)})}let h=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.showArtifacts()},b=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.hideArtifacts()},T=F=>{let B=F.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&nn.upsertArtifact(B.artifact)},W=F=>{let B=F.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&nn.selectArtifact(B.id)},z=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let sr=qb(r.persistState);if(sr&&N()){let l=zb(sr.storage),u=`${sr.keyPrefix}widget-open`,h=`${sr.keyPrefix}widget-voice`,b=`${sr.keyPrefix}widget-voice-mode`;if(l){let T=((_d=sr.persist)==null?void 0:_d.openState)&&l.getItem(u)==="true",W=(($d=sr.persist)==null?void 0:$d.voiceState)&&l.getItem(h)==="true",z=((jd=sr.persist)==null?void 0:jd.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{nn.open(),setTimeout(()=>{var F;if(W||z)nn.startVoiceRecognition();else if((F=sr.persist)!=null&&F.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Ud=sr.persist)!=null&&Ud.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(qd=sr.persist)!=null&&qd.voiceState&&(o.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),o.on("user:message",F=>{l.setItem(b,F.viaVoice?"true":"false")})),sr.clearOnChatClear){let F=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(b)},B=()=>F();window.addEventListener("persona:clear-chat",B),dt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&N()&&setTimeout(()=>{nn.open()},0),ds(),Ia||Xu().then(()=>{_&&(ss++,Mr.clear(),$s(Ve,_.getMessages(),Ie))}).catch(()=>{}),nn};var Vb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Kb=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Gb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Jb=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},of=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},lc=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=""},sf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",lc(e)},sc=e=>{e.style.transition=""},ac=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=""},ic=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ki=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Qb=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Xb=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},af=(e,t,n,r,s,o,a)=>{var x,v,M,S,R,O;let i=Xn(o),d=i.reveal==="push";Qb(e,t,n,r,d),Xb(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,m=(S=(M=o==null?void 0:o.launcher)==null?void 0:M.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=m:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ac(t),sc(r),sf(r),ic(n),Ki(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((O=(R=o==null?void 0:o.launcher)==null?void 0:R.zIndex)!=null?O: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"),sf(r),Kb(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",ac(t),sc(r),ic(n),Ki(s,r);let k=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=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=A,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",sc(r),lc(r),Ki(s,r);let k=Vb(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),A=i.animate?"margin-left 180ms ease":"none",H=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=A,t.style.marginLeft=`${H}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="",ac(t),lc(r),ic(n),Ki(s,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",H=!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",Gb(r,i.maxHeight),r.style.overflow=k||H?"hidden":"visible",r.style.transition=A,k&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Yb=(e,t)=>{let n=e.ownerDocument.createElement("div");return of(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){of(n,r)},destroy(){n.remove()}}},Zb=(e,t)=>{var O,k,I,A;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),m=(k=(O=t==null?void 0:t.launcher)==null?void 0:O.enabled)==null||k?(A=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),Xn(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{af(a,i,d,c,p,t,m)}),f.observe(a))},v=!1,M=()=>{af(a,i,d,c,p,t,m),x(),m&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Jb(a,Xn(t)))},S=a.ownerDocument.defaultView,R=()=>{M()};return S==null||S.addEventListener("resize",R),Xn(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(H){let D=H.launcherEnabled?H.open:!0;m!==D&&(m=D,M())},updateConfig(H){var D,N;t=H,((N=(D=t==null?void 0:t.launcher)==null?void 0:D.enabled)!=null?N:!0)===!1&&(m=!0),M()},destroy(){S==null||S.removeEventListener("resize",R),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},La=(e,t)=>on(t)?Zb(e,t):Yb(e,t);var cc={},ex=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},tx=()=>{try{if(typeof cc!="undefined"&&cc.url)return new URL("../widget.css",cc.url).href}catch{}return null},lf=(e,t)=>{let n=tx(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},dc=e=>{var M;let t=ex(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=La(t,s),a,i=[],d=(S,R)=>{var A,H;let k=!((H=(A=R==null?void 0:R.launcher)==null?void 0:A.enabled)!=null?H:!0)||on(R),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 D=S.attachShadow({mode:"open"});D.appendChild(I),lf(D,r)}else S.appendChild(I),lf(S,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},m=()=>{let S=d(o.host,s);a=Vi(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};m(),(M=e.onChatReady)==null||M.call(e);let g=S=>{f(),o.destroy(),o=La(t,S),s=S,m()},x={update(S){var H,D,N,L,U,V;let R={...s,...S,launcher:{...(H=s==null?void 0:s.launcher)!=null?H:{},...(D=S==null?void 0:S.launcher)!=null?D:{},dock:{...(L=(N=s==null?void 0:s.launcher)==null?void 0:N.dock)!=null?L:{},...(V=(U=S==null?void 0:S.launcher)==null?void 0:U.dock)!=null?V:{}}}},O=on(s),k=on(R),I=Eo(s),A=Eo(R);if(O!==k||I!==A){g(R);return}s=R,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(S,R,O){if(R==="host")return o.host;if(R in S)return Reflect.get(S,R,O);let k=a[R];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var mf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),nx=new Set(["button","a","input","select","textarea","details","summary"]),rx=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),pc=/\b(product|card|item|listing|result)\b/i,mc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ox=3e3,sx=100;function gf(e){let t=typeof e.className=="string"?e.className:"";if(pc.test(t)||e.id&&pc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&pc.test(r.value))return!0}return!1}function ff(e){var t;return mc.test(((t=e.textContent)!=null?t:"").trim())}function hf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function ax(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function cf(e){let t=e.match(mc);return t?t[0]:null}function df(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function ix(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var lx="commerce-card",cx="result-card";function pf(e){return!gf(e)||!ff(e)||!hf(e)&&!ax(e)?0:5200}function uf(e){var r;return!gf(e)||ff(e)||!hf(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 gc=[{id:lx,scoreElement(e){return pf(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||mc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(pf(e)===0)return null;let{title:n,href:r}=df(e),s=(p=(c=cf(((d=e.textContent)!=null?d:"").trim()))!=null?c:cf(t.text))!=null?p:"",o=ix(e);return[r&&n?`[${n}](${r})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
112
|
+
`)}},{id:cx,scoreElement(e){return uf(e)},formatSummary(e,t){if(uf(e)===0)return null;let{title:n,href:r}=df(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
113
|
+
`)}}];function dx(){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,m,f,g,x,v,M,S,R,O,k,I,A;let t=(p=e.options)!=null?p:{},n=(f=(m=t.maxElements)!=null?m:e.maxElements)!=null?f:80,r=(x=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?x:".persona-host",s=(M=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?M:200,o=(R=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?R:!0,a=(O=t.root)!=null?O:e.root,i=(k=t.mode)!=null?k:"structured",d=(I=t.maxCandidates)!=null?I:Math.max(500,n*10),c=(A=e.rules)!=null?A:gc;return i==="simple"&&e.rules&&e.rules.length>0?(dx(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function uc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ux=["data-testid","data-product","data-action","data-id","data-name","data-type"];function mx(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"||nx.has(t)||n&&rx.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function yf(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 gx(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function fc(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${uc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of ux){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${uc(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>uc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function fx(e){return e==="static"?sx:ox}function bf(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:fc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:mx(e),attributes:gx(e)}}function hx(e,t,n,r){let s=fx(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function yx(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 bx(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(mf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!yf(c)){i=a.nextNode();continue}let m=bf(c,e.maxTextLength),f=m.text.length>0,g=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(M=>M==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:x,formattingRule:v}=hx(c,m,e.rules,n);s.push({el:c,domIndex:o,enriched:m,score:x,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return m!==f?m-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;yx(d,c)||d.push(c)}return d.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return m!==f?m-f:m===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let m={...c.enriched};return p&&(m.formattedSummary=p),m})}function xx(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(mf.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!yf(d)){o=s.nextNode();continue}let p=bf(d,e.maxTextLength),m=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!m&&!f){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function xf(e={}){var r;let t=px(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?xx(t,n):bx(t,n):[]}var Gi=100;function vf(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
112
114
|
${a.map(i=>`- ${i.split(`
|
|
113
115
|
`).join(`
|
|
114
116
|
`)}`).join(`
|
|
@@ -122,7 +124,7 @@ ${a.join(`
|
|
|
122
124
|
${a.join(`
|
|
123
125
|
`)}`)}return r.join(`
|
|
124
126
|
|
|
125
|
-
`)}function
|
|
127
|
+
`)}function wf(){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 Cf(){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 Sf(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:Hr(e.colors.primary,.95),100:Hr(e.colors.primary,.9),200:Hr(e.colors.primary,.8),300:Hr(e.colors.primary,.7),400:Hr(e.colors.primary,.6),500:e.colors.primary,600:Hr(e.colors.primary,.8),700:Hr(e.colors.primary,.7),800:Hr(e.colors.primary,.6),900:Hr(e.colors.primary,.5),950:Hr(e.colors.primary,.45)}}),{...t,palette:n}}}}function Af(){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 Tf(){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 Hr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Ef(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var vx={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"}}},Mf={components:{panel:{borderRadius:"0",shadow:"none"}}},hc={id:"shop",label:"Shopping Assistant",config:{theme:vx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Qn},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?"]}},yc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Mf}},bc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Mf}},xc={shop:hc,minimal:yc,fullscreen:bc};function kf(e){return xc[e]}var Lf=dc;function eo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function wx(e){if(e)return{getHeaders:eo(e.getHeaders),onFeedback:eo(e.onFeedback),onCopy:eo(e.onCopy),requestMiddleware:eo(e.requestMiddleware),actionHandlers:eo(e.actionHandlers),actionParsers:eo(e.actionParsers),postprocessMessage:eo(e.postprocessMessage),contextProviders:eo(e.contextProviders),streamParser:eo(e.streamParser)}}var Pf=`({ text, message }: any) => {
|
|
126
128
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
127
129
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
128
130
|
let cleanJson = jsonSource
|
|
@@ -135,7 +137,7 @@ ${a.join(`
|
|
|
135
137
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
136
138
|
} catch (e) { return null; }
|
|
137
139
|
return null;
|
|
138
|
-
}`,
|
|
140
|
+
}`,If=`function(ctx) {
|
|
139
141
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
140
142
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
141
143
|
var cleanJson = jsonSource
|
|
@@ -148,7 +150,7 @@ ${a.join(`
|
|
|
148
150
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
149
151
|
} catch (e) { return null; }
|
|
150
152
|
return null;
|
|
151
|
-
}`,
|
|
153
|
+
}`,Rf=`(action: any, context: any) => {
|
|
152
154
|
if (action.type !== 'nav_then_click') return;
|
|
153
155
|
const payload = action.payload || action.raw || {};
|
|
154
156
|
const url = payload?.page;
|
|
@@ -165,7 +167,7 @@ ${a.join(`
|
|
|
165
167
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
166
168
|
window.location.href = targetUrl;
|
|
167
169
|
return { handled: true, displayText: text };
|
|
168
|
-
}`,
|
|
170
|
+
}`,Wf=`function(action, context) {
|
|
169
171
|
if (action.type !== 'nav_then_click') return;
|
|
170
172
|
var payload = action.payload || action.raw || {};
|
|
171
173
|
var url = payload.page;
|
|
@@ -182,26 +184,26 @@ ${a.join(`
|
|
|
182
184
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
183
185
|
window.location.href = targetUrl;
|
|
184
186
|
return { handled: true, displayText: text };
|
|
185
|
-
}`,
|
|
187
|
+
}`,Cx=`(parsed: any) => {
|
|
186
188
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
187
189
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
188
190
|
if (parsed.action === 'message') return parsed.text || '';
|
|
189
191
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
190
192
|
return parsed.text || null;
|
|
191
|
-
}`,
|
|
193
|
+
}`,Sx=`function(parsed) {
|
|
192
194
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
193
195
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
194
196
|
if (parsed.action === 'message') return parsed.text || '';
|
|
195
197
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
196
198
|
return parsed.text || null;
|
|
197
|
-
}`;function
|
|
198
|
-
`)}function
|
|
199
|
-
`)}function vx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Pa(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Qi(e," ")),r.push(...Xi(e," ",n)),r.push(...Yi(e," ")),r.push(...Zi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${fx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Ef}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Ef}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${kf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${kf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
200
|
-
`)}function
|
|
201
|
-
`)}function
|
|
199
|
+
}`;function Ax(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Ji(e){var t,n;return(n=(t=e.parserType)!=null?t:Ax(e.streamParser))!=null?n:"plain"}function Qi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function Xi(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Yi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Zi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function vc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Hf(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),Hf(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function ko(e,t,n,r){n&&(e.push(`${r}${t}: {`),Hf(e,n,`${r} `),e.push(`${r}},`))}function Pa(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Bf(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:wx(n.hooks)}:void 0;return t==="esm"?Tx(r,s):t==="script-installer"?kx(r,s):t==="script-advanced"?Px(r,s):t==="react-component"?Ex(r,s):t==="react-advanced"?Mx(r,s):Lx(r,s)}function Tx(e,t){let n=t==null?void 0:t.hooks,r=Ji(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Pa(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(o,"theme",e.theme," "),e.launcher&&ko(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Qi(e," ")),o.push(...Xi(e," ",n)),o.push(...Yi(e," ")),o.push(...Zi(e," ")),o.push(...vc(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
200
|
+
`)}function Ex(e,t){let n=t==null?void 0:t.hooks,r=Ji(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Pa(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(o,"theme",e.theme," "),e.launcher&&ko(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Qi(e," ")),o.push(...Xi(e," ",n)),o.push(...Yi(e," ")),o.push(...Zi(e," ")),o.push(...vc(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
|
|
201
|
+
`)}function Mx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Pa(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Qi(e," ")),r.push(...Xi(e," ",n)),r.push(...Yi(e," ")),r.push(...Zi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Cx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Pf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Pf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Rf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Rf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
202
|
+
`)}function Df(e){var s;let t=Ji(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(c[p]=m)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function kx(e,t){let n=Df(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lr}/dist/install.global.js" data-config='${o}'></script>`}function Lx(e,t){let n=t==null?void 0:t.hooks,r=Ji(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Pa(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(o,"theme",e.theme," "),e.launcher&&ko(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Qi(e," ")),o.push(...Xi(e," ",n)),o.push(...Yi(e," ")),o.push(...Zi(e," ")),o.push(...vc(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
203
|
+
`)}function Px(e,t){let n=t==null?void 0:t.hooks,r=Df(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
202
204
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
203
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${
|
|
204
|
-
`)}var
|
|
205
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${lr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${Sx});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${If}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${If}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Wf}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Wf}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Pa(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
206
|
+
`)}var Nf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Of=.1,Ff=.15,_f=1.5,wc=24,$f=40,Ix=`
|
|
205
207
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
206
208
|
.persona-dc-root {
|
|
207
209
|
display: flex;
|
|
@@ -442,5 +444,5 @@ ${a.join(`
|
|
|
442
444
|
min-height: 300px;
|
|
443
445
|
}
|
|
444
446
|
}
|
|
445
|
-
`;function
|
|
447
|
+
`;function Rx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ix,document.head.appendChild(e)}function Wx(e,t){let n=e.clientWidth-wc*2-$f,r=e.clientHeight-wc*2-$f;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Hx(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="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 jf(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Rx();let p=Math.max(0,Math.min(r,n.length-1)),m=s,f=o,g=null,x=1,v=!1,M=y("div","persona-dc-root"),S=y("div","persona-dc-toolbar"),R=y("div","persona-dc-toolbar-lead"),O=y("div","persona-dc-toolbar-trail"),k=qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>te(-1)}),I=y("div");I.style.position="relative";let A=y("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let H=y("span","persona-dc-title-text"),D=y("span","persona-dc-title-chevron"),N=xe("chevron-down",12,"currentColor",2);N&&D.appendChild(N),A.append(H,D);let L=y("div","persona-dc-dropdown");L.setAttribute("role","listbox"),L.style.display="none";let U=!1;function V(){L.innerHTML="";for(let we=0;we<n.length;we++){let Ye=n[we],Ge=y("button","persona-dc-dropdown-item");Ge.type="button",Ge.setAttribute("role","option"),Ge.setAttribute("aria-current",we===p?"true":"false");let Oe=y("span");if(Oe.textContent=Ye.title,Ge.appendChild(Oe),Ye.description){let de=y("span","persona-dc-dropdown-desc");de.textContent=Ye.description,Ge.appendChild(de)}Ge.addEventListener("click",()=>{Ie(),ze(we)}),L.appendChild(Ge)}}function ne(){U=!U,L.style.display=U?"":"none",A.setAttribute("aria-expanded",U?"true":"false"),U&&V()}function Ie(){U&&(U=!1,L.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",we=>{we.stopPropagation(),ne()});let Ue=()=>Ie();document.addEventListener("click",Ue),I.append(A,L);let Ae=qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>te(1)}),Le=y("span","persona-dc-counter");R.append(k,I,Ae,Le);let _e=null;i&&(_e=Ca({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:we=>{m=we,re.dataset.device=m,g=null,Q()}}),O.appendChild(_e.element));let ye=null;if(a){let we=y("div","persona-dc-zoom-controls"),Ye=qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let de=g!=null?g:x;g=Math.max(Ff,de-Of),Q()}});ye=y("span","persona-dc-zoom-level"),ye.title="Reset to 100%",ye.style.cursor="pointer",ye.addEventListener("click",()=>{g=1,Q()});let Ge=qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let de=g!=null?g:x;g=Math.min(_f,de+Of),Q()}}),Oe=qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,Q()}});we.append(Ye,ye,Ge,Oe),O.appendChild(we)}if(d){let we=y("div","persona-dc-separator");O.appendChild(we);let Ye=Ca({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:Ge=>{f=Ge,re.dataset.colorScheme=f,oe()}});O.appendChild(Ye.element)}let De=y("div","persona-dc-separator");O.appendChild(De);let ie=qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});O.appendChild(ie),S.append(R,O);let X=y("div","persona-dc-stage"),re=y("div","persona-dc-iframe-wrapper");re.dataset.device=m,re.dataset.colorScheme=f;let ce=y("iframe","persona-dc-iframe");ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ce.setAttribute("loading","lazy"),ce.title=n[p].title,re.appendChild(ce),X.appendChild(re),M.append(S,X),e.appendChild(M);function oe(){var we;try{let Ye=(we=ce.contentDocument)==null?void 0:we.body;if(!Ye)return;f==="dark"?Ye.classList.add("theme-dark"):Ye.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>oe());function J(){let we=n[p];H.textContent=we.title,Le.textContent=`${p+1} / ${n.length}`,ce.title=we.title}function te(we){let Ye=((p+we)%n.length+n.length)%n.length;ze(Ye)}function ze(we){we<0||we>=n.length||(p=we,ce.src=n[p].url,J(),c==null||c(p,n[p]))}function Q(){var Ge;if(v)return;let we=(Ge=Nf[m])!=null?Ge:Nf.desktop;x=Wx(X,we);let Ye=Math.max(Ff,Math.min(_f,g!=null?g:x));Hx(re,ce,we,Ye,m),ye&&(ye.textContent=`${Math.round(Ye*100)}%`)}let le=new ResizeObserver(()=>Q());le.observe(X),J(),ce.src=n[p].url,requestAnimationFrame(()=>Q());function We(){v||(v=!0,le.disconnect(),document.removeEventListener("click",Ue),M.remove())}return{element:M,goTo:ze,next:()=>te(1),prev:()=>te(-1),getIndex:()=>p,setDevice(we){m=we,re.dataset.device=we,_e==null||_e.setSelected(we),g=null,Q()},setColorScheme(we){f=we,re.dataset.colorScheme=we},setZoom(we){g=we,Q()},destroy:We}}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});
|
|
446
448
|
//# sourceMappingURL=index.cjs.map
|