@runtypelabs/persona 4.14.0 → 4.15.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/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-DveIaNx6.d.cts → types-BpWGm7_6.d.cts} +17 -0
- package/dist/animations/{types-DveIaNx6.d.ts → types-BpWGm7_6.d.ts} +17 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-QJ4LV2KW.js +1 -0
- package/dist/codegen.cjs +12 -11
- package/dist/codegen.js +14 -13
- package/dist/{context-mentions-ONG7A7M6.js → context-mentions-BTSTIBFC.js} +1 -1
- package/dist/context-mentions.cjs +11 -8
- package/dist/context-mentions.d.cts +241 -16
- package/dist/context-mentions.d.ts +241 -16
- package/dist/context-mentions.js +11 -8
- package/dist/index.cjs +67 -66
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +301 -41
- package/dist/index.d.ts +301 -41
- package/dist/index.global.js +59 -56
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +67 -66
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +241 -16
- package/dist/smart-dom-reader.d.ts +241 -16
- package/dist/theme-editor-preview.cjs +66 -66
- package/dist/theme-editor-preview.d.cts +255 -17
- package/dist/theme-editor-preview.d.ts +255 -17
- package/dist/theme-editor-preview.js +56 -56
- package/dist/theme-editor.cjs +5 -5
- package/dist/theme-editor.d.cts +242 -17
- package/dist/theme-editor.d.ts +242 -17
- package/dist/theme-editor.js +7 -7
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +38 -0
- package/dist/theme-reference.d.ts +38 -0
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/ask-user-question-tool.ts +10 -7
- package/src/components/artifact-preview.ts +1 -1
- package/src/components/composer-parts.test.ts +103 -4
- package/src/components/composer-parts.ts +53 -15
- package/src/components/messages.ts +5 -2
- package/src/components/panel.ts +31 -5
- package/src/components/pill-composer-builder.test.ts +18 -0
- package/src/components/suggestions.test.ts +233 -0
- package/src/components/suggestions.ts +463 -81
- package/src/components/widget-view.ts +4 -0
- package/src/defaults.ts +5 -3
- package/src/generated/runtype-openapi-contract.ts +17 -0
- package/src/index-core.ts +18 -2
- package/src/launcher-global.ts +1 -1
- package/src/plugins/types.ts +71 -3
- package/src/presets.ts +3 -3
- package/src/session.ts +10 -8
- package/src/styles/widget-styles.test.ts +162 -0
- package/src/styles/widget.css +430 -0
- package/src/suggest-replies-tool.test.ts +233 -2
- package/src/suggest-replies-tool.ts +115 -39
- package/src/theme-editor/preview-utils.test.ts +34 -0
- package/src/theme-editor/preview-utils.ts +77 -2
- package/src/theme-editor/sections.test.ts +33 -0
- package/src/theme-editor/sections.ts +53 -5
- package/src/theme-reference.ts +9 -2
- package/src/types/theme.ts +32 -0
- package/src/types.ts +152 -16
- package/src/ui.detached-panel.test.ts +1 -1
- package/src/ui.suggest-replies.test.ts +1066 -1
- package/src/ui.ts +268 -20
- package/src/utils/artifact-file.test.ts +1 -1
- package/src/utils/code-generators.test.ts +40 -0
- package/src/utils/code-generators.ts +22 -0
- package/src/utils/config-merge.test.ts +24 -0
- package/src/utils/icons.test.ts +26 -0
- package/src/utils/icons.ts +8 -0
- package/src/utils/theme.test.ts +79 -0
- package/src/utils/tokens.ts +64 -0
- package/dist/chunk-MMUPR2JW.js +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
"use strict";var mh=Object.create;var Ua=Object.defineProperty;var hh=Object.getOwnPropertyDescriptor;var yh=Object.getOwnPropertyNames;var bh=Object.getPrototypeOf,vh=Object.prototype.hasOwnProperty;var Tr=(e,t)=>()=>(e&&(t=e(e=0)),t);var za=(e,t)=>{for(var n in t)Ua(e,n,{get:t[n],enumerable:!0})},Ip=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of yh(t))!vh.call(e,r)&&r!==n&&Ua(e,r,{get:()=>t[r],enumerable:!(o=hh(t,r))||o.enumerable});return e};var Ts=(e,t,n)=>(n=e!=null?mh(bh(e)):{},Ip(t||!e||!e.__esModule?Ua(n,"default",{value:e,enumerable:!0}):n,e)),xh=e=>Ip(Ua({},"__esModule",{value:!0}),e);var Bp={};za(Bp,{DOMPurify:()=>Hp.default,Marked:()=>Wp.Marked});var Wp,Hp,Dp=Tr(()=>{"use strict";Wp=require("marked"),Hp=Ts(require("dompurify"),1)});var Br,dc=Tr(()=>{"use strict";Br=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function Ty(e){return e.replace(/\/+$/,"")}async function My(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var ui,Fu=Tr(()=>{"use strict";dc();ui=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Br(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${Ty(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await My(a));let i=a.body.getReader();for(;;){let{done:d,value:p}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var fi,_u=Tr(()=>{"use strict";fi=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var $u={};za($u,{FallbackSpeechEngine:()=>fi,RuntypeSpeechEngine:()=>ui});var ju=Tr(()=>{"use strict";Fu();_u()});var zu={};za(zu,{createReconnectController:()=>ky});function ky(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},d=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",d),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},u=y=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},y)}),b=()=>{let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let k=e.buildErrorContent("Connection lost and the response could not be resumed.");k?e.appendMessage({id:`reconnect-failed-${y?.executionId??e.nextSequence()}`,role:"assistant",content:k,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let y=e.config.reconnect?.backoffMs??Ey,C=e.config.reconnect?.maxAttempts??y.length,k=e.config.reconnectStream;if(!k){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),H=L.lastEventId,E=new AbortController;e.setAbortController(E),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let P=null;try{let _=await k({executionId:L.executionId,after:L.lastEventId,signal:E.signal});_&&_.ok&&_.body&&(P=_.body)}catch{P=null}if(E.signal.aborted)return;if(P){let _=e.getMessages().find(w=>w.id===L.assistantMessageId)?.content,q=typeof _=="string"?_:"";try{await e.resumeConnect(P,L.assistantMessageId,q)}catch{}if(E.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==H&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(y[Math.min(t-1,y.length-1)]??1e3),E.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,p(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var Ey,qu=Tr(()=>{"use strict";Ey=[1e3,2e3,4e3,8e3,8e3]});var cC={};za(cC,{ASK_USER_QUESTION_CLIENT_TOOL:()=>ic,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ac,ASK_USER_QUESTION_TOOL_NAME:()=>Ls,AgentWidgetClient:()=>Zo,AgentWidgetSession:()=>Or,AttachmentManager:()=>nr,BrowserSpeechEngine:()=>Mo,DEFAULT_COMPONENTS:()=>xc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>hi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>ln,DEFAULT_PALETTE:()=>bc,DEFAULT_SEMANTIC:()=>vc,DEFAULT_WIDGET_CONFIG:()=>it,PRESETS:()=>bd,PRESET_FULLSCREEN:()=>yd,PRESET_MINIMAL:()=>hd,PRESET_SHOP:()=>md,ReadAloudController:()=>tr,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ya,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>oc,SUGGEST_REPLIES_TOOL_NAME:()=>Tn,THEME_ZONES:()=>sf,VERSION:()=>Jn,WEBMCP_TOOL_PREFIX:()=>Sn,WebMcpBridge:()=>Pr,accessibilityPlugin:()=>nm,animationsPlugin:()=>om,applyFeaturePreferences:()=>Zc,applyThemeVariables:()=>or,attachHeaderToContainer:()=>sr,brandPlugin:()=>rm,buildComposer:()=>qr,buildDefaultHeader:()=>Wc,buildHeader:()=>Zn,buildHeaderWithLayout:()=>zr,buildMinimalHeader:()=>Hc,builtInClientToolsForDispatch:()=>Wr,canonicalArtifactDisplayMode:()=>en,collectEnrichedPageContext:()=>em,componentRegistry:()=>Mn,createActionManager:()=>ia,createAgentExperience:()=>al,createAskUserQuestionBubble:()=>vu,createBestAvailableVoiceProvider:()=>pi,createBubbleWithLayout:()=>Zf,createCSATFeedback:()=>ol,createComboButton:()=>Ti,createComponentMiddleware:()=>Rg,createComponentStreamParser:()=>el,createDefaultSanitizer:()=>Gl,createDemoCarousel:()=>Am,createDirectivePostprocessor:()=>zp,createDropdownMenu:()=>Lo,createFlexibleJsonStreamParser:()=>Au,createIconButton:()=>dt,createImagePart:()=>Lu,createJsonStreamParser:()=>si,createLabelButton:()=>Yn,createLocalStorageAdapter:()=>Zi,createMarkdownProcessor:()=>Ms,createMarkdownProcessorFromConfig:()=>Yo,createMessageActions:()=>jc,createNPSFeedback:()=>rl,createPlainTextParser:()=>oi,createPlugin:()=>im,createRegexJsonParser:()=>ri,createRovingTablist:()=>Ji,createSlashCommandsSource:()=>Ug,createStandardBubble:()=>Vr,createStaticMentionSource:()=>jg,createTextPart:()=>So,createTheme:()=>$s,createThemeObserver:()=>Fr,createToggleGroup:()=>Qn,createTypingIndicator:()=>ar,createVoiceProvider:()=>To,createWidgetHostLayout:()=>ca,createXmlParser:()=>ai,default:()=>dm,defaultActionHandlers:()=>ur,defaultJsonActionParser:()=>aa,defaultMentionFilter:()=>ll,defaultParseRules:()=>fd,detectColorScheme:()=>js,directivePostprocessor:()=>qp,ensureAskUserQuestionSheet:()=>Ir,escapeHtml:()=>Rn,extractComponentDirectiveFromMessage:()=>nl,fileToImagePart:()=>Ru,formatEnrichedContext:()=>tm,generateAssistantMessageId:()=>Ao,generateCodeSnippet:()=>hm,generateMessageId:()=>Mu,generateStableSelector:()=>gd,generateUserMessageId:()=>Hr,getActiveTheme:()=>Eo,getColorScheme:()=>Ci,getDisplayText:()=>ku,getHeaderLayout:()=>Bc,getImageParts:()=>Pu,getPreset:()=>cm,hasComponentDirective:()=>la,hasImages:()=>ci,headerLayouts:()=>Fi,highContrastPlugin:()=>am,initAgentWidget:()=>cd,isAskUserQuestionMessage:()=>Vn,isComponentDirectiveType:()=>Lg,isDockedMountMode:()=>Pt,isSuggestRepliesMessage:()=>Is,isVoiceSupported:()=>Os,isWebMcpToolName:()=>ho,latestAgentSuggestions:()=>Qa,listRegisteredStreamAnimations:()=>jf,loadMarkdownParsers:()=>Vl,markdownPostprocessor:()=>Kl,mergeWithDefaults:()=>Nr,normalizeContent:()=>Eu,normalizeMediaType:()=>yo,onMarkdownParsersReady:()=>Er,parseAskUserQuestionPayload:()=>Kn,parseSuggestRepliesPayload:()=>sc,parseWidgetPreferenceSlice:()=>Qc,pickBestVoice:()=>Dr,pluginRegistry:()=>sa,reducedMotionPlugin:()=>sm,registerStreamAnimationPlugin:()=>_f,removeAskUserQuestionSheet:()=>xo,renderComponentDirective:()=>tl,renderLoadingIndicatorWithFallback:()=>_c,renderLucideIcon:()=>re,resolveArtifactDisplay:()=>Yl,resolveArtifactDisplayMode:()=>In,resolveConfigPreferences:()=>ra,resolveDockConfig:()=>tn,resolveSanitizer:()=>kr,resolveTokens:()=>vi,stripWebMcpPrefix:()=>Ka,themeToCssVariables:()=>xi,unregisterStreamAnimationPlugin:()=>$f,validateImageFile:()=>Iu,validateTheme:()=>Cc});module.exports=xh(cC);var Fp=require("marked"),_p=Ts(require("dompurify"),1);var Mr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:hC,load:Ch,provide:wh,getSync:ql}=Mr({fallbackImport:()=>Promise.resolve().then(()=>(Dp(),Bp))}),qa=new Set,Op=()=>{let e=[...qa];qa.clear();for(let t of e)try{t()}catch{}};var Vl=()=>{let e=ql();return e?Promise.resolve(e):Ch().then(t=>(Op(),t))},Er=e=>ql()?()=>{}:(qa.add(e),Vl().catch(()=>{}),()=>{qa.delete(e)}),Np=e=>{wh(e),Op()},zn=ql;Np({Marked:Fp.Marked,DOMPurify:_p.default});var Ah=e=>{if(e)return e},Ms=e=>{let t=null;return n=>{let o=zn();if(!o)return Rn(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Ah(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Yo=e=>e?Ms({markedOptions:e.options,renderer:e.renderer}):Ms(),Sh=Ms(),Kl=e=>Sh(e),Rn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),jp=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),$p=e=>`%%FORM_PLACEHOLDER_${e}%%`,Up=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=$p(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=$p(t.length);return t.push({token:s,type:r}),s}),n},zp=e=>{let t=Yo(e);return n=>{let o=[],r=Up(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${jp(i)}"></div>`;s=s.replace(d,c)}),s}},qp=e=>{let t=[],n=Up(e,t),o=Kl(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${jp(s)}"></div>`;o=o.replace(a,d)}),o};var Th={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Mh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Gl=()=>{let e=null;return t=>{let n=zn();if(!n)return Rn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Mh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Th)}},kr=e=>e===!1?null:typeof e=="function"?e:Gl();var Vp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Kp=e=>e.includes("|"),Gp=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())},Eh=e=>`| ${e.join(" | ")} |`,kh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Ph=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Jp=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!
|
|
3
|
-
`):e};var
|
|
1
|
+
"use strict";var Nh=Object.create;var Ga=Object.defineProperty;var Fh=Object.getOwnPropertyDescriptor;var _h=Object.getOwnPropertyNames;var $h=Object.getPrototypeOf,jh=Object.prototype.hasOwnProperty;var Lr=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ja=(e,t)=>{for(var n in t)Ga(e,n,{get:t[n],enumerable:!0})},Yp=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of _h(t))!jh.call(e,r)&&r!==n&&Ga(e,r,{get:()=>t[r],enumerable:!(o=Fh(t,r))||o.enumerable});return e};var Ws=(e,t,n)=>(n=e!=null?Nh($h(e)):{},Yp(t||!e||!e.__esModule?Ga(n,"default",{value:e,enumerable:!0}):n,e)),Uh=e=>Yp(Ga({},"__esModule",{value:!0}),e);var eu={};Ja(eu,{DOMPurify:()=>Zp.default,Marked:()=>Qp.Marked});var Qp,Zp,tu=Lr(()=>{"use strict";Qp=require("marked"),Zp=Ws(require("dompurify"),1)});var _r,hc=Lr(()=>{"use strict";_r=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function Jy(e){return e.replace(/\/+$/,"")}async function Xy(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var yi,rg=Lr(()=>{"use strict";hc();yi=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new _r(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${Jy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await Xy(a));let i=a.body.getReader();for(;;){let{done:d,value:p}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var bi,sg=Lr(()=>{"use strict";bi=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var ag={};Ja(ag,{FallbackSpeechEngine:()=>bi,RuntypeSpeechEngine:()=>yi});var ig=Lr(()=>{"use strict";rg();sg()});var cg={};Ja(cg,{createReconnectController:()=>Qy});function Qy(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},d=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",d),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},u=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),v=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let b=e.config.reconnect?.backoffMs??Yy,C=e.config.reconnect?.maxAttempts??b.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),W=L.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let k=null;try{let F=await E({executionId:L.executionId,after:L.lastEventId,signal:A.signal});F&&F.ok&&F.body&&(k=F.body)}catch{k=null}if(A.signal.aborted)return;if(k){let F=e.getMessages().find(S=>S.id===L.assistantMessageId)?.content,q=typeof F=="string"?F:"";try{await e.resumeConnect(k,L.assistantMessageId,q)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==W&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(b[Math.min(t-1,b.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&v()};return{begin(){t=0,p(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var Yy,dg=Lr(()=>{"use strict";Yy=[1e3,2e3,4e3,8e3,8e3]});var OC={};Ja(OC,{ASK_USER_QUESTION_CLIENT_TOOL:()=>gc,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>uc,ASK_USER_QUESTION_TOOL_NAME:()=>Ns,AgentWidgetClient:()=>rr,AgentWidgetSession:()=>jr,AttachmentManager:()=>ir,BrowserSpeechEngine:()=>Lo,DEFAULT_COMPONENTS:()=>Mc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ci,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>dn,DEFAULT_PALETTE:()=>Sc,DEFAULT_SEMANTIC:()=>Tc,DEFAULT_WIDGET_CONFIG:()=>at,PRESETS:()=>Td,PRESET_FULLSCREEN:()=>Sd,PRESET_MINIMAL:()=>Ad,PRESET_SHOP:()=>wd,ReadAloudController:()=>ar,SUGGEST_REPLIES_CLIENT_TOOL:()=>ni,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>cc,SUGGEST_REPLIES_TOOL_NAME:()=>En,THEME_ZONES:()=>Sg,VERSION:()=>Qn,WEBMCP_TOOL_PREFIX:()=>Mn,WebMcpBridge:()=>Hr,accessibilityPlugin:()=>Cm,animationsPlugin:()=>wm,applyFeaturePreferences:()=>ad,applyThemeVariables:()=>lr,attachHeaderToContainer:()=>dr,brandPlugin:()=>Am,buildComposer:()=>Xr,buildDefaultHeader:()=>_c,buildHeader:()=>no,buildHeaderWithLayout:()=>Jr,buildMinimalHeader:()=>$c,builtInClientToolsForDispatch:()=>Nr,canonicalArtifactDisplayMode:()=>nn,collectEnrichedPageContext:()=>vm,componentRegistry:()=>kn,createActionManager:()=>fa,createAgentExperience:()=>gl,createAskUserQuestionBubble:()=>Nu,createBestAvailableVoiceProvider:()=>hi,createBubbleWithLayout:()=>vf,createCSATFeedback:()=>dl,createComboButton:()=>Li,createComponentMiddleware:()=>Xf,createComponentStreamParser:()=>il,createDefaultSanitizer:()=>ec,createDemoCarousel:()=>jm,createDirectivePostprocessor:()=>cu,createDropdownMenu:()=>Ho,createFlexibleJsonStreamParser:()=>ju,createIconButton:()=>it,createImagePart:()=>Ju,createJsonStreamParser:()=>di,createLabelButton:()=>eo,createLocalStorageAdapter:()=>al,createMarkdownProcessor:()=>Hs,createMarkdownProcessorFromConfig:()=>tr,createMessageActions:()=>Jc,createNPSFeedback:()=>pl,createPlainTextParser:()=>li,createPlugin:()=>Mm,createRegexJsonParser:()=>ci,createRovingTablist:()=>nl,createSlashCommandsSource:()=>lm,createStandardBubble:()=>Yr,createStaticMentionSource:()=>im,createTextPart:()=>ko,createTheme:()=>Gs,createThemeObserver:()=>zr,createToggleGroup:()=>to,createTypingIndicator:()=>pr,createVoiceProvider:()=>Po,createWidgetHostLayout:()=>ha,createXmlParser:()=>pi,default:()=>Pm,defaultActionHandlers:()=>yr,defaultJsonActionParser:()=>ga,defaultMentionFilter:()=>ml,defaultParseRules:()=>xd,detectColorScheme:()=>Js,directivePostprocessor:()=>du,ensureAskUserQuestionSheet:()=>Or,escapeHtml:()=>Hn,extractComponentDirectiveFromMessage:()=>cl,fileToImagePart:()=>Xu,formatEnrichedContext:()=>xm,generateAssistantMessageId:()=>Eo,generateCodeSnippet:()=>Bm,generateMessageId:()=>qu,generateStableSelector:()=>Cd,generateUserMessageId:()=>Fr,getActiveTheme:()=>Ro,getColorScheme:()=>Mi,getDisplayText:()=>Ku,getHeaderLayout:()=>jc,getImageParts:()=>Gu,getPreset:()=>km,hasComponentDirective:()=>ma,hasImages:()=>fi,headerLayouts:()=>qi,highContrastPlugin:()=>Tm,initAgentWidget:()=>hd,isAskUserQuestionMessage:()=>Jn,isComponentDirectiveType:()=>Jf,isDockedMountMode:()=>Pt,isSuggestRepliesMessage:()=>or,isVoiceSupported:()=>zs,isWebMcpToolName:()=>vo,latestAgentSuggestions:()=>oi,listRegisteredStreamAnimations:()=>af,loadMarkdownParsers:()=>Ql,markdownPostprocessor:()=>Zl,mergeWithDefaults:()=>Ur,normalizeContent:()=>Vu,normalizeMediaType:()=>xo,onMarkdownParsersReady:()=>Ir,parseAskUserQuestionPayload:()=>Xn,parseSuggestRepliesPayload:()=>pc,parseWidgetPreferenceSlice:()=>sd,pickBestVoice:()=>$r,pluginRegistry:()=>ua,reducedMotionPlugin:()=>Sm,registerStreamAnimationPlugin:()=>rf,removeAskUserQuestionSheet:()=>Ao,renderComponentDirective:()=>ll,renderLoadingIndicatorWithFallback:()=>Kc,renderLucideIcon:()=>re,resolveArtifactDisplay:()=>oc,resolveArtifactDisplayMode:()=>Bn,resolveConfigPreferences:()=>pa,resolveDockConfig:()=>on,resolveSanitizer:()=>Wr,resolveTokens:()=>Si,stripWebMcpPrefix:()=>Qa,themeToCssVariables:()=>Ti,unregisterStreamAnimationPlugin:()=>sf,validateImageFile:()=>Yu,validateTheme:()=>Ec});module.exports=Uh(OC);var ru=require("marked"),su=Ws(require("dompurify"),1);var Rr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:zC,load:zh,provide:qh,getSync:Yl}=Rr({fallbackImport:()=>Promise.resolve().then(()=>(tu(),eu))}),Xa=new Set,nu=()=>{let e=[...Xa];Xa.clear();for(let t of e)try{t()}catch{}};var Ql=()=>{let e=Yl();return e?Promise.resolve(e):zh().then(t=>(nu(),t))},Ir=e=>Yl()?()=>{}:(Xa.add(e),Ql().catch(()=>{}),()=>{Xa.delete(e)}),ou=e=>{qh(e),nu()},Kn=Yl;ou({Marked:ru.Marked,DOMPurify:su.default});var Vh=e=>{if(e)return e},Hs=e=>{let t=null;return n=>{let o=Kn();if(!o)return Hn(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Vh(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},tr=e=>e?Hs({markedOptions:e.options,renderer:e.renderer}):Hs(),Kh=Hs(),Zl=e=>Kh(e),Hn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),iu=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),au=e=>`%%FORM_PLACEHOLDER_${e}%%`,lu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=au(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=au(t.length);return t.push({token:s,type:r}),s}),n},cu=e=>{let t=tr(e);return n=>{let o=[],r=lu(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${iu(i)}"></div>`;s=s.replace(d,c)}),s}},du=e=>{let t=[],n=lu(e,t),o=Zl(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${iu(s)}"></div>`;o=o.replace(a,d)}),o};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"]},Jh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ec=()=>{let e=null;return t=>{let n=Kn();if(!n)return Hn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Jh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Gh)}},Wr=e=>e===!1?null:typeof e=="function"?e:ec();var pu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,uu=e=>e.includes("|"),gu=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())},Xh=e=>`| ${e.join(" | ")} |`,Yh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Qh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fu=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!uu(r)||pu.test(r)||!pu.test(s))continue;let a=gu(r).length;if(a<1)continue;let i=Yh(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let d=o+2;for(;d<t.length;d++){let p=t[d];if(p.trim()===""||!uu(p))break;let c=Xh(Qh(gu(p),a));t[d]!==c&&(t[d]=c,n=!0)}o=d-1}return n?t.join(`
|
|
3
|
+
`):e};var mu="var(--persona-md-table-scroll-fade, 24px)",hu=new WeakSet;function bu(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function yu(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":mu),e.style.setProperty("--persona-fade-r",r<=1?"0px":mu)}function tc(e){hu.has(e)||(hu.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&yu(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(yu)}var Mn="webmcp:",nc=new Map,vu=e=>{nc.clear();for(let t of e){let n=t.title?.trim();n&&nc.set(t.name,n)}},Bs=e=>nc.get(Qa(e)),Ya={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},xu=null;function wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${Zh(t.join(""))}`}function Cu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Zh(e){let t=Cu(e,0).toString(36),n=Cu(e,2654435761).toString(36);return`${t}.${n}`}var Hr=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Ya.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}vu(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=ty(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Tn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Tn(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Qa(t),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Tn(`Failed to read WebMCP registry: ${C}`)}vu(a);let i=a.find(b=>b.name===s);if(!i)return Tn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Tn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Tn("Aborted by cancel()");let d=Bs(s),p={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return Tn("User declined the tool call.");if(o?.aborted)return Tn("Aborted by cancel()");let c=new AbortController,u=!1,v=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let b=await r.executeTool(i,sy(n),{signal:c.signal});return ny(b)}catch(b){if(u)return Tn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Tn("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Tn(C)}finally{clearTimeout(v),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(xu?await xu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ya.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ya.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??oy;try{return await n(t)}catch(o){return Ya.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>ey(t,o))}},Qa=e=>e.startsWith(Mn)?e.slice(Mn.length):e,vo=e=>e.startsWith(Mn),ey=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},ty=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},ny=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:ay(t)}]}},Tn=e=>({isError:!0,content:[{type:"text",text:e}]}),oy=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=ry(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
6
|
${t}`:"")+(e.description?`
|
|
7
7
|
|
|
8
|
-
${e.description}`:"");return window.confirm(n)},Bh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Dh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Oh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function en(e){return e==="card"?"collapsed":e}function yo(e){return e.split(";",1)[0].trim().toLowerCase()}function Nh(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(yo(r)===t)return{mode:en(s),selector:yo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(yo(r)===o)return{mode:en(s),selector:o}}function Yl(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:en(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?yo(t.file.mimeType):void 0,d=i?Nh(o.files.byMediaType,i):void 0;if(i&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:i,selector:d.selector}};if(o.files.default)return{mode:en(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:en(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:en(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:en(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:en(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function In(e,t){return Yl(e,t).mode}function ks(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Fh="agent_",_h="flow_";function ru(e){return e.startsWith(Fh)?{kind:"agentId",agentId:e}:e.startsWith(_h)?{kind:"flowId",flowId:e}:null}function su(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let p=ru(i);if(p)return p;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let r=ru(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var bo=require("partial-json");var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var au=()=>document.createDocumentFragment(),Fe=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},qn=(...e)=>e.filter(Boolean).join(" ");var Ls="ask_user_question",Ps=8,Lr="data-persona-ask-sheet-for",$h="Other",jh="Other\u2026",lu="Type your own answer here",cu="Send",Uh="Next",zh="Back",qh="Submit all",Vh="Skip",Kh=3,Ql="data-ask-current-index",Zl="data-ask-question-count",du="data-ask-answers",ec="data-ask-grouped",pu="data-ask-layout",Gh=e=>e.layout==="pills"?"pills":"rows",Jh=e=>e.getAttribute(pu)==="pills"?"pills":"rows",iu=!1,uu=e=>e.replace(/["\\]/g,"\\$&"),Vn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ls,Ga=e=>e?.features?.askUserQuestion??{},Kn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,bo.parse)(r,bo.STR|bo.OBJ|bo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Rs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ps&&!iu&&(iu=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ps}.`)),t.slice(0,Ps)},Xh=e=>Rs(e)[0]??null,Yh=(e,t)=>Rs(e)[t]??null,fu=(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))},gu=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Qh=(e,t,n,o)=>{let s=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let p=m("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=gu(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Zh=e=>{let n=m("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},ey=(e,t,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(d.length===0&&!n){for(let c=0;c<Kh;c++)s.appendChild(Zh(o));return s}if(d.forEach((c,u)=>{s.appendChild(Qh(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?$h:jh;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(d.length)),u.setAttribute("data-ask-other-row","true");let b=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??lu,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(f),u.appendChild(b);let y=gu(o,a,d.length);y&&u.appendChild(y),s.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},mu=(e,t)=>{let o=m("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??lu,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??cu,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},ty=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??cu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ny=(e,t,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??zh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Vh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?n.submitAllLabel??qh:n.nextLabel??Uh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Qo=e=>{let t=e.getAttribute(du);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},hu=(e,t)=>{e.setAttribute(du,JSON.stringify(t))},hn=e=>{let t=Number(e.getAttribute(Ql)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},oy=(e,t)=>{e.setAttribute(Ql,String(Math.max(0,Math.floor(t))))},Rr=e=>{let t=Number(e.getAttribute(Zl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vo=e=>e.getAttribute(ec)==="true",ry=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},sy=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ja=(e,t)=>{let{payload:n}=Kn(t),o=Rs(n),r=Qo(e),s={},a=new Set;return o.forEach((i,d)=>{let p=typeof i?.question=="string"?i.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},yu=e=>{let t=Qo(e),n=hn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",c=r.has(p);d.setAttribute("aria-pressed",c?"true":"false"),d.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},bu=e=>{if(!vo(e))return;let t=Qo(e),n=hn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},tc=(e,t,n)=>{let o=Ga(n),r=Jh(e),{payload:s,complete:a}=Kn(t),i=vo(e),d=hn(e),p=Rr(e),c=i?Yh(s,d):Xh(s),u=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${d+1}/${p}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let H=typeof c?.question=="string"?c.question:"";y.textContent=H,y.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let H=ey(c,o,a,r);C.replaceWith(H)}if(r!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(mu(o,r))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!k?e.appendChild(ty(o)):(!u||i)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let H=ny(d,p,o);L?L.replaceWith(H):e.appendChild(H)}else L&&L.remove();yu(e),bu(e)},ay=(e,t,n)=>{let o=Ga(t),r=Gh(o),s=e.toolCall.id,a=Rs(n),i=Math.max(1,a.length),d=i>1,p=ry(e,a),c=d?sy(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Lr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Zl,String(i)),u.setAttribute(Ql,String(c)),u.setAttribute(ec,d?"true":"false"),u.setAttribute(pu,r),hu(u,p),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),fu(u,o);let b=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let y=m("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),u.appendChild(b);let k=m("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),r!=="rows"&&u.appendChild(mu(o,r)),tc(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},iy=(e,t,n)=>{let{payload:o}=Kn(t),r=Math.max(1,Rs(o).length);r>Rr(e)&&(e.setAttribute(Zl,String(r)),r>1&&!vo(e)&&e.setAttribute(ec,"true")),tc(e,t,n)},vu=(e,t)=>{let n=m("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Ga(t);fu(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=Kn(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Ir=(e,t,n)=>{if(!n||!Vn(e)||Ga(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Lr}]`).forEach(p=>{p.getAttribute(Lr)!==r&&p.remove()});let a=n.querySelector(`[${Lr}="${uu(r)}"]`);if(a){iy(a,e,t);return}let{payload:i}=Kn(e),d=ay(e,t,i);n.appendChild(d)},xo=(e,t)=>{if(!e)return;let n=t?`[${Lr}="${uu(t)}"]`:`[${Lr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},nc=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),Co=(e,t)=>{let n=Qo(e),o=hn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,hu(e,n),yu(e),bu(e)},Xa=(e,t,n,o)=>{let r=Rr(e),s=Math.max(0,Math.min(r-1,o));oy(e,s),tc(e,t,n)};var Tn="suggest_replies";var oc={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},Ya={name:Tn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:oc,origin:"sdk",annotations:{readOnlyHint:!0}},rc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Is=e=>e.variant==="tool"&&e.toolCall?.name===Tn,sc=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Qa=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Is(n))continue;let o=sc(n.toolCall?.args);return o.length>0?o:null}return null},xu=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var ac={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ps,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},ic={name:Ls,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:ac,origin:"sdk",annotations:{readOnlyHint:!0}},Wr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(ic),xu(e)&&t.push(Ya),t};var Gn=require("partial-json"),Za=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},ry=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)}},sy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ay=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function nn(e){return e==="card"?"collapsed":e}function xo(e){return e.split(";",1)[0].trim().toLowerCase()}function iy(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(xo(r)===t)return{mode:nn(s),selector:xo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(xo(r)===o)return{mode:nn(s),selector:o}}function oc(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:nn(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?xo(t.file.mimeType):void 0,d=i?iy(o.files.byMediaType,i):void 0;if(i&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:i,selector:d.selector}};if(o.files.default)return{mode:nn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:nn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:nn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:nn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:nn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Bn(e,t){return oc(e,t).mode}function Ds(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var ly="agent_",cy="flow_";function Au(e){return e.startsWith(ly)?{kind:"agentId",agentId:e}:e.startsWith(cy)?{kind:"flowId",flowId:e}:null}function Su(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let p=Au(i);if(p)return p;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let r=Au(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Co=require("partial-json");var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Tu=()=>document.createDocumentFragment(),Ie=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Gn=(...e)=>e.filter(Boolean).join(" ");var Ns="ask_user_question",Os=8,Br="data-persona-ask-sheet-for",dy="Other",py="Other\u2026",Eu="Type your own answer here",ku="Send",uy="Next",gy="Back",fy="Submit all",my="Skip",hy=3,rc="data-ask-current-index",sc="data-ask-question-count",Pu="data-ask-answers",ac="data-ask-grouped",Lu="data-ask-layout",yy=e=>e.layout==="pills"?"pills":"rows",by=e=>e.getAttribute(Lu)==="pills"?"pills":"rows",Mu=!1,Ru=e=>e.replace(/["\\]/g,"\\$&"),Jn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ns,Za=e=>e?.features?.askUserQuestion??{},Xn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,Co.parse)(r,Co.STR|Co.OBJ|Co.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Fs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Os&&!Mu&&(Mu=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Os}.`)),t.slice(0,Os)},vy=e=>Fs(e)[0]??null,xy=(e,t)=>Fs(e)[t]??null,Iu=(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))},Wu=(e,t,n)=>{if(e!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Cy=(e,t,n,o)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let p=h("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=Wu(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},wy=e=>{let n=h("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},Ay=(e,t,n,o)=>{let s=h("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(d.length===0&&!n){for(let c=0;c<hy;c++)s.appendChild(wy(o));return s}if(d.forEach((c,u)=>{s.appendChild(Cy(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?dy:py;if(o==="rows"){let u=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(d.length)),u.setAttribute("data-ask-other-row","true");let v=h("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Eu,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),v.appendChild(f),u.appendChild(v);let b=Wu(o,a,d.length);b&&u.appendChild(b),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},Hu=(e,t)=>{let o=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Eu,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??ku,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Sy=e=>{let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??ku,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ty=(e,t,n)=>{let o=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gy,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??my,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?n.submitAllLabel??fy:n.nextLabel??uy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},nr=e=>{let t=e.getAttribute(Pu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Bu=(e,t)=>{e.setAttribute(Pu,JSON.stringify(t))},bn=e=>{let t=Number(e.getAttribute(rc)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},My=(e,t)=>{e.setAttribute(rc,String(Math.max(0,Math.floor(t))))},Dr=e=>{let t=Number(e.getAttribute(sc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},wo=e=>e.getAttribute(ac)==="true",Ey=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},ky=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ei=(e,t)=>{let{payload:n}=Xn(t),o=Fs(n),r=nr(e),s={},a=new Set;return o.forEach((i,d)=>{let p=typeof i?.question=="string"?i.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},Du=e=>{let t=nr(e),n=bn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",c=r.has(p);d.setAttribute("aria-pressed",c?"true":"false"),d.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},Ou=e=>{if(!wo(e))return;let t=nr(e),n=bn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},ic=(e,t,n)=>{let o=Za(n),r=by(e),{payload:s,complete:a}=Xn(t),i=wo(e),d=bn(e),p=Dr(e),c=i?xy(s,d):vy(s),u=!!c?.multiSelect,v=e.querySelector('[data-ask-step-inline="true"]');v&&(v.textContent=i?`${d+1}/${p}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let W=typeof c?.question=="string"?c.question:"";b.textContent=W,b.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let W=Ay(c,o,a,r);C.replaceWith(W)}if(r!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(Hu(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(Sy(o)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=Ty(d,p,o);L?L.replaceWith(W):e.appendChild(W)}else L&&L.remove();Du(e),Ou(e)},Py=(e,t,n)=>{let o=Za(t),r=yy(o),s=e.toolCall.id,a=Fs(n),i=Math.max(1,a.length),d=i>1,p=Ey(e,a),c=d?ky(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Br,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(sc,String(i)),u.setAttribute(rc,String(c)),u.setAttribute(ac,d?"true":"false"),u.setAttribute(Lu,r),Bu(u,p),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Iu(u,o);let v=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",v.appendChild(f);let b=h("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",v.appendChild(b),u.appendChild(v);let E=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(Hu(o,r)),ic(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ly=(e,t,n)=>{let{payload:o}=Xn(t),r=Math.max(1,Fs(o).length);r>Dr(e)&&(e.setAttribute(sc,String(r)),r>1&&!wo(e)&&e.setAttribute(ac,"true")),ic(e,t,n)},Nu=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Za(t);Iu(n,o);let r=h("span","persona-ask-stub-label"),{complete:s}=Xn(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Or=(e,t,n)=>{if(!n||!Jn(e)||Za(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Br}]`).forEach(p=>{p.getAttribute(Br)!==r&&p.remove()});let a=n.querySelector(`[${Br}="${Ru(r)}"]`);if(a){Ly(a,e,t);return}let{payload:i}=Xn(e),d=Py(e,t,i);n.appendChild(d)},Ao=(e,t)=>{if(!e)return;let n=t?`[${Br}="${Ru(t)}"]`:`[${Br}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},lc=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),So=(e,t)=>{let n=nr(e),o=bn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Bu(e,n),Du(e),Ou(e)},ti=(e,t,n,o)=>{let r=Dr(e),s=Math.max(0,Math.min(r-1,o));My(e,s),ic(e,t,n)};var En="suggest_replies";var cc={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:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},ni={name:En,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts 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:cc,origin:"sdk",annotations:{readOnlyHint:!0}},dc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),or=e=>e.variant==="tool"&&e.toolCall?.name===En,pc=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let i=r.trim();return i?[i]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},oi=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!or(n))continue;let o=pc(n.toolCall?.args);return o.length>0?o:null}return null},Fu=new Set,Ry=(e,t,n)=>{let o=`${e}:${t}:${n}`;Fu.has(o)||(Fu.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},To=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let i=t?.[a],d=n?.[a];i===void 0||d===void 0||i!==d&&Ry(a,d,i)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var uc={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Os,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},gc={name:Ns,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:uc,origin:"sdk",annotations:{readOnlyHint:!0}},Nr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(gc),To(e).expose&&t.push(ni),t};var Yn=require("partial-json"),ri=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Mo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Iy=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},_u=e=>e.status==="complete"?Iy(e):e.status==="pending"?"Waiting":"",Wy=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var $u=e=>e.status==="complete"?Wy(e):"Using tool...",si=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},$s=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return si(t)},ai=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return si(t)},fc=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=$s(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ii=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&_s(o,n.slice(s,a.index),[]),a[1]!==void 0?_s(o,a[1],["bold"]):a[2]!==void 0?_s(o,a[2],["italic"]):a[3]!==void 0&&_s(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&_s(o,n.slice(s),[]),o},_s=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Hy=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Bs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},oi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ri=()=>{let e=dy();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},si=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Gn.parse)(n,Gn.STR|Gn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Za(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Za(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Au=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Za(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Za(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Gn.parse)(s,Gn.STR|Gn.OBJ),d=r(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ai=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Su="4.14.0";var Jn=Su;var uy="https://api.runtype.com/v1/dispatch",ii="https://api.runtype.com";function fy(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var cc=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 gy(e){switch(e){case"json":return si;case"regex-json":return ri;case"xml":return ai;default:return oi}}var Tu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function my(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Tu(n);if(!Tu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Bs(e);return Bs(t)!==null&&a===null?t:e}var Zo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??uy,this.headers={"Content-Type":"application/json","X-Persona-Version":Jn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??gy(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Pr(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=su(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ii}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ii}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let p=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:p}),p}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([p])=>p!=="sessionId"&&p!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(cc).map(p=>({id:p.id,role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:d}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,p=>{let c={...a,...p};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let p=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.status===429){let u=new Error(p.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(p.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let p=new Error("No response body received");throw n({type:"error",error:p}),p}d(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ii}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?ou(n):void 0,i=this.clientToolsFingerprintSessionId===t,d=s&&i&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let b=0;;b++){if(u=await o({...s&&(c||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ii}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(d.sessionId=a),r&&a){let p=[...Wr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,p,b=>{let f={...d,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(cc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let p=new Date(i.createdAt).getTime(),c=new Date(d.createdAt).getTime();return p-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Wr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(cc).sort((i,d)=>{let p=new Date(i.createdAt).getTime(),c=new Date(d.createdAt).getTime();return p-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,d]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=d);let s=[...Wr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},p=c=>o.current?o.current:d(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=p(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),p=0,c=()=>d+p++,u=T=>{let N=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,v=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,I=T.tools?T.tools.map(M=>({...M,chunks:M.chunks?[...M.chunks]:void 0})):void 0;return{...T,reasoning:N,toolCall:v,tools:I}},b=T=>{if(T.role!=="assistant"||T.variant)return!0;let N=Array.isArray(T.contentParts)&&T.contentParts.length>0,v=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||N||v||!!T.stopReason},f=T=>{b(T)&&n({type:"message",message:u(T)})},y=null,C=null,k={current:null},L={current:null},H=null,E="",P=new Map,_=new Map,q=new Map,w=new Map,z=new Map,V={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},O=T=>{if(T==null)return null;try{return String(T)}catch{return null}},j=T=>O(T.stepId??T.step_id??T.step??T.parentId??T.flowStepId??T.flow_step_id),Y=T=>O(T.callId??T.call_id??T.requestId??T.request_id??T.toolCallId??T.tool_call_id??T.stepId??T.step_id),be=o,ve=!1,Be=()=>{if(y)return y;let T,N="",v=H;return!ve&&be?(T=be,ve=!0,N=r??""):be&&v?T=`${be}_${v}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:T,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(y),y},se=(T,N)=>{V.lastId=N,T&&V.byStep.set(T,N)},he=(T,N)=>{let v=T.reasoningId??T.id,I=j(T);if(v){let W=String(v);return se(I,W),W}if(I){let W=V.byStep.get(I);if(W)return V.lastId=W,W}if(V.lastId&&!N)return V.lastId;if(!N)return null;let M=`reason-${c()}`;return se(I,M),M},ee=T=>{let N=w.get(T);if(N)return N;let v={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"streaming",chunks:[]}};return w.set(T,v),f(v),v},de=(T,N)=>{te.lastId=N,T&&te.byCall.set(T,N)},Z=new Set,ue=new Map,xe=new Set,ye=new Map,Se=T=>{if(!T)return!1;let N=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return N==="emit_artifact_markdown"||N==="emit_artifact_component"},lt=(T,N)=>{let v=T.toolId??T.id,I=Y(T);if(v){let W=String(v);return de(I,W),W}if(I){let W=te.byCall.get(I);if(W)return te.lastId=W,W}if(te.lastId&&!N)return te.lastId;if(!N)return null;let M=`tool-${c()}`;return de(I,M),M},Ee=T=>{let N=z.get(T);if(N)return N;let v={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:T,status:"pending"}};return z.set(T,v),f(v),v},De=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let N=Number(T);if(!Number.isNaN(N)&&Number.isFinite(N))return N;let v=Date.parse(T);if(!Number.isNaN(v))return v}return Date.now()},Ne=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},qe=new Map,Me=new Map,ce=new Map,Le=(T,N,v)=>{let I=ce.get(T);I||(I=[],ce.set(T,I));let M=0,W=I.length;for(;M<W;){let D=M+W>>>1;I[D].seq<N?M=D+1:W=D}I[M]?.seq===N?I[M]={seq:N,text:v}:I.splice(M,0,{seq:N,text:v});let G="";for(let D=0;D<I.length;D++)G+=I[D].text;return G},st=(T,N)=>{let v=Ne(N),I=Me.get(T.id),M=my(I,v);T.rawContent=M;let W=qe.get(T.id),G=We=>{let Ye=T.content??"";We.trim()!==""&&(Ye.trim().length===0||We.startsWith(Ye)||We.trimStart().startsWith(Ye.trim()))&&(T.content=We)},D=()=>{if(W){let We=W.close?.();We instanceof Promise&&We.catch(()=>{})}qe.delete(T.id),Me.delete(T.id),T.streaming=!1,f(T)};if(!W){G(v),D();return}let U=Bs(M);if(U!==null&&U.trim()!==""){G(U),D();return}let Q=We=>{let Ye=typeof We=="string"?We:We?.text??null;if(Ye!==null&&Ye.trim()!=="")return Ye;let rt=W.getExtractedText();return rt!==null&&rt.trim()!==""?rt:v},Ge;try{Ge=W.processChunk(M)}catch{G(v),D();return}if(Ge instanceof Promise){Ge.then(We=>{G(Q(We)),D()}).catch(()=>{G(v),D()});return}G(Q(Ge)),D()},xt=null,Lt=(T,N,v,I)=>{T.rawContent=N,qe.has(T.id)||qe.set(T.id,this.createStreamParser());let M=qe.get(T.id),W=N.trim().startsWith("{")||N.trim().startsWith("[");if(W&&Me.set(T.id,N),M.__isPlainTextParser===!0){T.content=I!==void 0?N:T.content+v,Me.delete(T.id),qe.delete(T.id),T.rawContent=void 0,f(T);return}let D=M.processChunk(N);if(D instanceof Promise)D.then(U=>{let Q=typeof U=="string"?U:U?.text??null;Q!==null&&Q.trim()!==""?(T.content=Q,f(T)):!W&&!N.trim().startsWith("<")&&(T.content=I!==void 0?N:T.content+v,Me.delete(T.id),qe.delete(T.id),T.rawContent=void 0,f(T))}).catch(()=>{T.content=I!==void 0?N:T.content+v,Me.delete(T.id),qe.delete(T.id),T.rawContent=void 0,f(T)});else{let U=typeof D=="string"?D:D?.text??null;U!==null&&U.trim()!==""?(T.content=U,f(T)):!W&&!N.trim().startsWith("<")&&(T.content=I!==void 0?N:T.content+v,Me.delete(T.id),qe.delete(T.id),T.rawContent=void 0,f(T))}},Tt=(T,N)=>{let v=N??T.content;if(v==null||v===""){T.streaming=!1,f(T);return}let M=Me.get(T.id)??Ne(v);T.rawContent=M;let W=qe.get(T.id),G=null,D=!1;if(W&&(G=W.getExtractedText(),G===null&&(G=Bs(M)),G===null)){let U=W.processChunk(M);U instanceof Promise?(D=!0,U.then(Q=>{let Ge=typeof Q=="string"?Q:Q?.text??null;Ge!==null&&(T.content=Ge,T.streaming=!1,qe.delete(T.id),Me.delete(T.id),f(T))}).catch(()=>{})):G=typeof U=="string"?U:U?.text??null}if(!D){G!==null&&G.trim()!==""?T.content=G:Me.has(T.id)||(T.content=Ne(v));let U=qe.get(T.id);if(U){let Q=U.close?.();Q instanceof Promise&&Q.catch(()=>{}),qe.delete(T.id)}Me.delete(T.id),T.streaming=!1,f(T)}},Oe=(T,N,v)=>{let I=_.get(T);if(I)return I;let M={id:`nested-${N}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:N}};return _.set(T,M),f(M),M},pe=[],et,Ie=new Map,ge=0,ie="agent",Re=!1,ct=null,fe=null,Ae=new Map,ne=this.config.iterationDisplay??"separate";for(et=()=>{for(let T=0;T<pe.length;T++){let N=pe[T].payloadType,v=pe[T].payload;if(!Re&&ie!=="flow"&&typeof v.stepType=="string"&&(ie="flow"),N==="reasoning_start"){let I=typeof v.id=="string"?v.id:null,M=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(I&&M){P.set(I,M),Oe(I,M,"reasoning");continue}let W=he(v,!0)??`reason-${c()}`,G=ee(W);G.reasoning=G.reasoning??{id:W,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??De(v.startedAt??v.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(G.reasoning.scope=v.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(N==="reasoning_delta"){let I=typeof v.id=="string"?v.id:null;if(I&&P.has(I)&&_.has(I)){let D=_.get(I),U=v.reasoningText??v.text??v.delta??"";U&&v.hidden!==!0&&D.reasoning&&(D.reasoning.chunks.push(String(U)),f(D));continue}let M=he(v,!1)??he(v,!0)??`reason-${c()}`,W=ee(M);W.reasoning=W.reasoning??{id:M,status:"streaming",chunks:[]},W.reasoning.startedAt=W.reasoning.startedAt??De(v.startedAt??v.timestamp);let G=v.reasoningText??v.text??v.delta??"";if(G&&v.hidden!==!0){let D=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(D!==void 0){let U=Le(M,D,String(G));W.reasoning.chunks=[U]}else W.reasoning.chunks.push(String(G))}if(W.reasoning.status=v.done?"complete":"streaming",v.done){W.reasoning.completedAt=De(v.completedAt??v.timestamp);let D=W.reasoning.startedAt??Date.now();W.reasoning.durationMs=Math.max(0,(W.reasoning.completedAt??Date.now())-D)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(N==="reasoning_complete"){let I=typeof v.id=="string"?v.id:null;if(I&&P.has(I)&&_.has(I)){let U=_.get(I);if(U.reasoning){let Q=typeof v.text=="string"?v.text:"";Q&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push(Q),U.reasoning.status="complete",U.streaming=!1,f(U)}P.delete(I),_.delete(I);continue}let M=he(v,!1)??he(v,!0)??`reason-${c()}`,W=typeof v.text=="string"?v.text:"";!w.get(M)&&(W||v.scope==="loop")&&ee(M);let G=w.get(M);if(G?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(G.reasoning.scope=v.scope),W&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(W),G.reasoning.status="complete",G.reasoning.completedAt=De(v.completedAt??v.timestamp);let U=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-U),G.streaming=!1,f(G)}let D=j(v);D&&V.byStep.delete(D)}else if(N==="tool_start"){y&&(y.streaming=!1,f(y),y=null),typeof v.iteration=="number"&&(ge=v.iteration);let I=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??lt(v,!0)??`tool-${c()}`,M=v.toolName??v.name;if(Se(M)){Z.add(I);continue}de(Y(v),I);let W=Ee(I),G=W.toolCall??{id:I,status:"pending"};G.name=M??G.name,G.status="running",v.parameters!==void 0?G.args=v.parameters:v.args!==void 0&&(G.args=v.args),G.startedAt=G.startedAt??De(v.startedAt??v.timestamp),G.completedAt=void 0,G.durationMs=void 0,W.toolCall=G,W.streaming=!0,v.executionId&&(W.agentMetadata={executionId:v.executionId,iteration:v.iteration}),f(W)}else if(N==="tool_output_delta"){let I=lt(v,!1)??lt(v,!0)??`tool-${c()}`;if(Z.has(I))continue;let M=Ee(I),W=M.toolCall??{id:I,status:"running"};W.startedAt=W.startedAt??De(v.startedAt??v.timestamp);let G=v.text??v.delta??v.message??"";G&&(W.chunks=W.chunks??[],W.chunks.push(String(G))),W.status="running",M.toolCall=W,M.streaming=!0;let D=v.agentContext;(D||v.executionId)&&(M.agentMetadata=M.agentMetadata??{executionId:D?.executionId??v.executionId,iteration:D?.iteration??v.iteration}),f(M)}else if(N==="tool_complete"){let I=lt(v,!1)??lt(v,!0)??`tool-${c()}`;if(Z.has(I)){Z.delete(I);continue}let M=Ee(I),W=M.toolCall??{id:I,status:"running"};W.status="complete",v.result!==void 0&&(W.result=v.result),typeof v.duration=="number"&&(W.duration=v.duration),W.completedAt=De(v.completedAt??v.timestamp);let G=v.duration??v.executionTime;if(typeof G=="number")W.durationMs=G;else{let Q=W.startedAt??Date.now();W.durationMs=Math.max(0,(W.completedAt??Date.now())-Q)}M.toolCall=W,M.streaming=!1;let D=v.agentContext;(D||v.executionId)&&(M.agentMetadata=M.agentMetadata??{executionId:D?.executionId??v.executionId,iteration:D?.iteration??v.iteration}),f(M);let U=Y(v);U&&te.byCall.delete(U)}else if(N==="await"&&v.toolName){let I=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,M=I??v.toolId??`local-${c()}`,W=Ee(M),G=v.toolName,D=v.origin==="webmcp"&&!ho(G)?`webmcp:${G}`:G,U=ho(D),Q=W.toolCall??{id:M,status:"pending"};Q.name=D,Q.args=v.parameters,Q.status=U?"running":"complete",Q.chunks=Q.chunks??[],Q.startedAt=Q.startedAt??De(v.startedAt??v.timestamp??v.awaitedAt),U?(Q.completedAt=void 0,Q.duration=void 0,Q.durationMs=void 0):Q.completedAt=Q.completedAt??Q.startedAt,W.toolCall=Q,W.streaming=!1,W.agentMetadata={...W.agentMetadata,executionId:v.executionId??W.agentMetadata?.executionId,awaitingLocalTool:!0,...I?{webMcpToolCallId:I}:{}},f(W)}else if(N==="text_start"){let I=typeof v.id=="string"?v.id:null,M=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(I&&M){P.set(I,M);continue}let W=y;W&&(ie==="flow"?(Tt(W),xt=W):(W.streaming=!1,f(W)),y=null),H=typeof v.id=="string"?v.id:H,E=""}else if(N==="text_delta"){let I=typeof v.id=="string"?v.id:null,M=I?P.get(I):void 0;if(I&&M){let G=typeof v.delta=="string"?v.delta:"",D=(q.get(I)??"")+G;if(q.set(I,D),D.trim()==="")continue;let U=Oe(I,M);U.agentMetadata={...U.agentMetadata,executionId:v.executionId,parentToolId:M},Lt(U,D,G,void 0);continue}if(H=typeof v.id=="string"?v.id:H,ie==="flow"){let G=typeof v.delta=="string"?v.delta:"";if(E+=G,E.trim()==="")continue;let D=Be();D.agentMetadata={executionId:v.executionId,iteration:v.iteration},Lt(D,E,G,void 0),C=D;continue}let W=Be();W.content+=v.delta??"",W.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:ct??void 0,agentName:fe?.agentName},C=W,f(W)}else if(N==="text_complete"){let I=typeof v.id=="string"?v.id:null;if(I&&P.has(I)){let W=_.get(I);W&&Tt(W),P.delete(I),q.delete(I),_.delete(I);continue}let M=y;M&&(ie==="flow"?(Tt(M),xt=M):((M.content??"")===""&&typeof v.text=="string"&&(M.content=v.text),M.streaming=!1,f(M)),y=null),H=null,E=""}else if(N==="step_complete"){let I=v.stepType,M=v.executionType;if(I==="tool"||M==="context")continue;if(v.success===!1){let W=v.error,G=typeof W=="string"&&W!==""?W:W!=null&&typeof W=="object"&&Reflect.has(W,"message")?String(W.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let D=y;D&&D.streaming&&(D.streaming=!1,f(D)),n({type:"status",status:"idle"});continue}{let W=xt;xt=null;let G=v.stopReason,D=v.result?.response;if(W)G&&(W.stopReason=G),D!=null?st(W,D):W.streaming!==!1&&(qe.delete(W.id),Me.delete(W.id),W.streaming=!1,f(W));else{let U=D!=null&&D!=="";if(U||G){let Q=Be();G&&(Q.stopReason=G),U?Tt(Q,D):(Q.streaming=!1,f(Q))}}continue}}else if(N==="execution_start")ie=v.kind==="flow"?"flow":"agent",Re=!0,ie==="agent"&&(fe={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:De(v.startedAt)});else if(N==="turn_start"){let I=typeof v.iteration=="number"?v.iteration:ge;if(I!==ge){if(fe&&(fe.currentIteration=I),ne==="separate"&&I>1){let M=y;M&&(M.streaming=!1,f(M),Ae.set(I-1,M),y=null)}ge=I}ct=typeof v.id=="string"?v.id:null,C=null}else if(N==="tool_input_delta"){let I=v.toolCallId??te.lastId;if(I){let M=z.get(I);M?.toolCall&&(M.toolCall.chunks=M.toolCall.chunks??[],M.toolCall.chunks.push(v.delta??""),f(M))}}else{if(N==="tool_input_complete")continue;if(N==="turn_complete"){let I=v.stopReason,M=y??C;if(I&&M!==null){let W=v.id;(!W||M.agentMetadata?.turnId===W)&&(M.stopReason=I,f(M))}ct===v.id&&(ct=null)}else if(N==="media_start"){let I=String(v.id);Ie.set(I,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(N==="media_delta"){let I=Ie.get(String(v.id));I&&typeof v.delta=="string"&&I.parts.push(v.delta)}else if(N==="media_complete"){let I=String(v.id),M=Ie.get(I);Ie.delete(I);let W=(typeof v.mediaType=="string"?v.mediaType:void 0)??M?.mediaType??"application/octet-stream",G=typeof v.data=="string"?v.data:void 0,D=typeof v.url=="string"?v.url:M&&M.parts.length>0?M.parts.join(""):void 0,U=null;if(G)U={type:"media",data:G,mediaType:W};else if(D){let Ye=W.toLowerCase();U={type:Ye==="image"||Ye.startsWith("image/")?"image-url":"file-url",url:D,mediaType:W}}let Q=v.toolCallId??M?.toolCallId,Ge=U?[U]:[],We=[];for(let Ye of Ge){if(!Ye||typeof Ye!="object")continue;let rt=Ye,K=typeof rt.type=="string"?rt.type:void 0,Ue=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",Ce=null,ze="";if(K==="media"){let _e=typeof rt.data=="string"?rt.data:void 0;if(!_e)continue;ze=Ue.length>0?Ue:"application/octet-stream",Ce=`data:${ze};base64,${_e}`}else if(K==="image-url"){let _e=typeof rt.url=="string"?rt.url:void 0;if(!_e)continue;ze=Ue,Ce=_e}else if(K==="file-url"){let _e=typeof rt.url=="string"?rt.url:void 0;if(!_e)continue;ze=Ue,Ce=_e}else continue;if(Ce)if(K==="image-url"||ze.startsWith("image/"))We.push({type:"image",image:Ce,...ze.includes("/")?{mimeType:ze}:{}});else if(ze.startsWith("audio/"))We.push({type:"audio",audio:Ce,mimeType:ze});else if(ze.startsWith("video/"))We.push({type:"video",video:Ce,mimeType:ze});else{let _e=ze||"application/octet-stream";We.push({type:"file",data:Ce,mimeType:_e,filename:fy(_e)})}}if(We.length>0){let Ye=c(),rt=Q,Ue={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Ye}`:String(Ye)}`,role:"assistant",content:"",contentParts:We,createdAt:new Date().toISOString(),streaming:!1,sequence:Ye,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ge}};f(Ue);let Ce=y;Ce&&(Ce.streaming=!1,f(Ce)),y=null,k.current=null}}else if(N==="execution_complete"){let I=v.kind??ie;I==="agent"&&fe&&(fe.status=v.success?"complete":"error",fe.completedAt=De(v.completedAt),fe.stopReason=v.stopReason);let M=y;M&&(I==="flow"&&M.streaming!==!1?Tt(M):(M.streaming=!1,f(M)),y=null),H=null,E="",xt=null,n({type:"status",status:"idle",terminal:!0})}else if(N==="execution_error"){let I=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(I)})}else if(N!=="ping"){if(N==="approval_start"){let I=v.approvalId??`approval-${c()}`,M={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:fe?.agentId??"virtual",executionId:v.executionId??fe?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(M)}else if(N==="step_await"&&v.awaitReason==="approval_required"){let I=v.approvalId??`approval-${c()}`,M={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:fe?.agentId??"virtual",executionId:v.executionId??fe?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(M)}else if(N==="approval_complete"){let I=v.approvalId;if(I){let W={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:v.decision??"approved",agentId:fe?.agentId??"virtual",executionId:v.executionId??fe?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(W)}}else if(N==="artifact_start"||N==="artifact_delta"||N==="artifact_update"||N==="artifact_complete"){if(N==="artifact_start"){let I=v.artifactType,M=String(v.id),W=typeof v.title=="string"?v.title:void 0,G=v.file,D;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(D={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:M,artifactType:I,title:W,component:typeof v.component=="string"?v.component:void 0,...D?{file:D}:{}});let U=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(ye.set(M,{markdown:"",title:W,file:D,...U?{props:U}:{}}),!xe.has(M)){xe.add(M);let Q=In(this.config.features?.artifacts,{artifactType:I,...D?{file:D}:{}}),Ge=typeof v.component=="string"?v.component:void 0,We={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ks(Q,{artifactId:M,title:W,artifactType:I,status:"streaming",...D?{file:D}:{},...Ge?{component:Ge}:{}})};ue.set(M,We),f(We)}}else if(N==="artifact_delta"){let I=String(v.id),M=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:I,artDelta:M});let W=ye.get(I);W&&(W.markdown+=M)}else if(N==="artifact_update"){let I=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:I,component:typeof v.component=="string"?v.component:void 0});let M=ye.get(String(v.id));M&&(M.props={...M.props??{},...I})}else if(N==="artifact_complete"){let I=String(v.id);n({type:"artifact_complete",id:I});let M=ue.get(I);if(M){M.streaming=!1;try{let W=JSON.parse(M.rawContent??"{}");if(W.props){W.props.status="complete";let G=ye.get(I);G?.markdown&&(W.props.markdown=G.markdown),G?.file&&(W.props.file=G.file),W.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(W.props.componentProps=G.props)}M.rawContent=JSON.stringify(W)}catch{}ye.delete(I),f(M),ue.delete(I)}}}else if(N==="transcript_insert"){let I=v.message;if(!I||typeof I!="object")continue;let M=String(I.id??`msg-${c()}`),W=I.role,D={id:M,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(f(D),D.rawContent)try{let Q=JSON.parse(D.rawContent)?.props?.artifactId;typeof Q=="string"&&xe.add(Q)}catch{}y=null,k.current=null,qe.delete(M),Me.delete(M)}else if(N==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let I=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(I)});let M=y;M&&M.streaming&&(M.streaming=!1,f(M)),n({type:"status",status:"idle"})}}else if(N==="step_error"||N==="dispatch_error"||N==="flow_error"){let I=null;if(v.error instanceof Error)I=v.error;else if(N==="dispatch_error"){let M=v.message??v.error;M!=null&&M!==""&&(I=new Error(String(M)))}else{let M=v.error;typeof M=="string"&&M!==""?I=new Error(M):M!=null&&typeof M=="object"&&Reflect.has(M,"message")&&(I=new Error(String(M.message??M)))}if(I){n({type:"error",error:I});let M=y;M&&M.streaming&&(M.streaming=!1,f(M)),n({type:"status",status:"idle"})}}}}}pe.length=0};;){let{done:T,value:N}=await s.read();if(T)break;i+=a.decode(N,{stream:!0});let v=i.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},js=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ci=()=>{let e=Hy();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},di=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Yn.parse)(n,Yn.STR|Yn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ri(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ri(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ju=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?ri(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ri(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Yn.parse)(s,Yn.STR|Yn.OBJ),d=r(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},pi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Uu="4.15.0";var Qn=Uu;var Dy="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function Oy(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var mc=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 Ny(e){switch(e){case"json":return di;case"regex-json":return ci;case"xml":return pi;default:return li}}var zu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Fy(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=zu(n);if(!zu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=js(e);return js(t)!==null&&a===null?t:e}var rr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Dy,this.headers={"Content-Type":"application/json","X-Persona-Version":Qn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Ny(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Hr(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Su(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Qn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Qn},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let p=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:p}),p}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([p])=>p!=="sessionId"&&p!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(mc).map(p=>({id:p.id,role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:d}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,p=>{let c={...a,...p};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Qn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let p=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.status===429){let u=new Error(p.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(p.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let p=new Error("No response body received");throw n({type:"error",error:p}),p}d(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?wu(n):void 0,i=this.clientToolsFingerprintSessionId===t,d=s&&i&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let v=0;;v++){if(u=await o({...s&&(c||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&v===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ui}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(d.sessionId=a),r&&a){let p=[...Nr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,p,v=>{let f={...d,...v};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(mc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let p=new Date(i.createdAt).getTime(),c=new Date(d.createdAt).getTime();return p-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Nr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(mc).sort((i,d)=>{let p=new Date(i.createdAt).getTime(),c=new Date(d.createdAt).getTime();return p-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,d]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=d);let s=[...Nr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},p=c=>o.current?o.current:d(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=p(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),p=0,c=()=>d+p++,u=w=>{let j=w.reasoning?{...w.reasoning,chunks:[...w.reasoning.chunks]}:void 0,y=w.toolCall?{...w.toolCall,chunks:w.toolCall.chunks?[...w.toolCall.chunks]:void 0}:void 0,R=w.tools?w.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...w,reasoning:j,toolCall:y,tools:R}},v=w=>{if(w.role!=="assistant"||w.variant)return!0;let j=Array.isArray(w.contentParts)&&w.contentParts.length>0,y=typeof w.rawContent=="string"&&w.rawContent.trim()!=="";return typeof w.content=="string"&&w.content.trim()!==""||j||y||!!w.stopReason},f=w=>{v(w)&&n({type:"message",message:u(w)})},b=null,C=null,E={current:null},L={current:null},W=null,A="",k=new Map,F=new Map,q=new Map,S=new Map,V=new Map,G={lastId:null,byStep:new Map},oe={lastId:null,byCall:new Map},N=w=>{if(w==null)return null;try{return String(w)}catch{return null}},U=w=>N(w.stepId??w.step_id??w.step??w.parentId??w.flowStepId??w.flow_step_id),Z=w=>N(w.callId??w.call_id??w.requestId??w.request_id??w.toolCallId??w.tool_call_id??w.stepId??w.step_id),he=o,ve=!1,ue=()=>{if(b)return b;let w,j="",y=W;return!ve&&he?(w=he,ve=!0,j=r??""):he&&y?w=`${he}_${y}`:w=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:w,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(b),b},ne=(w,j)=>{G.lastId=j,w&&G.byStep.set(w,j)},fe=(w,j)=>{let y=w.reasoningId??w.id,R=U(w);if(y){let D=String(y);return ne(R,D),D}if(R){let D=G.byStep.get(R);if(D)return G.lastId=D,D}if(G.lastId&&!j)return G.lastId;if(!j)return null;let I=`reason-${c()}`;return ne(R,I),I},te=w=>{let j=S.get(w);if(j)return j;let y={id:`reason-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:w,status:"streaming",chunks:[]}};return S.set(w,y),f(y),y},de=(w,j)=>{oe.lastId=j,w&&oe.byCall.set(w,j)},Q=new Set,me=new Map,xe=new Set,ye=new Map,Ae=w=>{if(!w)return!1;let j=w.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},Ee=(w,j)=>{let y=w.toolId??w.id,R=Z(w);if(y){let D=String(y);return de(R,D),D}if(R){let D=oe.byCall.get(R);if(D)return oe.lastId=D,D}if(oe.lastId&&!j)return oe.lastId;if(!j)return null;let I=`tool-${c()}`;return de(R,I),I},Se=w=>{let j=V.get(w);if(j)return j;let y={id:`tool-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:w,status:"pending"}};return V.set(w,y),f(y),y},Te=w=>{if(typeof w=="number"&&Number.isFinite(w))return w;if(typeof w=="string"){let j=Number(w);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let y=Date.parse(w);if(!Number.isNaN(y))return y}return Date.now()},Fe=w=>{if(typeof w=="string")return w;if(w==null)return"";try{return JSON.stringify(w)}catch{return String(w)}},Ue=new Map,ke=new Map,ce=new Map,We=(w,j,y)=>{let R=ce.get(w);R||(R=[],ce.set(w,R));let I=0,D=R.length;for(;I<D;){let H=I+D>>>1;R[H].seq<j?I=H+1:D=H}R[I]?.seq===j?R[I]={seq:j,text:y}:R.splice(I,0,{seq:j,text:y});let O="";for(let H=0;H<R.length;H++)O+=R[H].text;return O},ot=(w,j)=>{let y=Fe(j),R=ke.get(w.id),I=Fy(R,y);w.rawContent=I;let D=Ue.get(w.id),O=we=>{let rt=w.content??"";we.trim()!==""&&(rt.trim().length===0||we.startsWith(rt)||we.trimStart().startsWith(rt.trim()))&&(w.content=we)},H=()=>{if(D){let we=D.close?.();we instanceof Promise&&we.catch(()=>{})}Ue.delete(w.id),ke.delete(w.id),w.streaming=!1,f(w)};if(!D){O(y),H();return}let X=js(I);if(X!==null&&X.trim()!==""){O(X),H();return}let ie=we=>{let rt=typeof we=="string"?we:we?.text??null;if(rt!==null&&rt.trim()!=="")return rt;let nt=D.getExtractedText();return nt!==null&&nt.trim()!==""?nt:y},Pe;try{Pe=D.processChunk(I)}catch{O(y),H();return}if(Pe instanceof Promise){Pe.then(we=>{O(ie(we)),H()}).catch(()=>{O(y),H()});return}O(ie(Pe)),H()},bt=null,Lt=(w,j,y,R)=>{w.rawContent=j,Ue.has(w.id)||Ue.set(w.id,this.createStreamParser());let I=Ue.get(w.id),D=j.trim().startsWith("{")||j.trim().startsWith("[");if(D&&ke.set(w.id,j),I.__isPlainTextParser===!0){w.content=R!==void 0?j:w.content+y,ke.delete(w.id),Ue.delete(w.id),w.rawContent=void 0,f(w);return}let H=I.processChunk(j);if(H instanceof Promise)H.then(X=>{let ie=typeof X=="string"?X:X?.text??null;ie!==null&&ie.trim()!==""?(w.content=ie,f(w)):!D&&!j.trim().startsWith("<")&&(w.content=R!==void 0?j:w.content+y,ke.delete(w.id),Ue.delete(w.id),w.rawContent=void 0,f(w))}).catch(()=>{w.content=R!==void 0?j:w.content+y,ke.delete(w.id),Ue.delete(w.id),w.rawContent=void 0,f(w)});else{let X=typeof H=="string"?H:H?.text??null;X!==null&&X.trim()!==""?(w.content=X,f(w)):!D&&!j.trim().startsWith("<")&&(w.content=R!==void 0?j:w.content+y,ke.delete(w.id),Ue.delete(w.id),w.rawContent=void 0,f(w))}},Tt=(w,j)=>{let y=j??w.content;if(y==null||y===""){w.streaming=!1,f(w);return}let I=ke.get(w.id)??Fe(y);w.rawContent=I;let D=Ue.get(w.id),O=null,H=!1;if(D&&(O=D.getExtractedText(),O===null&&(O=js(I)),O===null)){let X=D.processChunk(I);X instanceof Promise?(H=!0,X.then(ie=>{let Pe=typeof ie=="string"?ie:ie?.text??null;Pe!==null&&(w.content=Pe,w.streaming=!1,Ue.delete(w.id),ke.delete(w.id),f(w))}).catch(()=>{})):O=typeof X=="string"?X:X?.text??null}if(!H){O!==null&&O.trim()!==""?w.content=O:ke.has(w.id)||(w.content=Fe(y));let X=Ue.get(w.id);if(X){let ie=X.close?.();ie instanceof Promise&&ie.catch(()=>{}),Ue.delete(w.id)}ke.delete(w.id),w.streaming=!1,f(w)}},Oe=(w,j,y)=>{let R=F.get(w);if(R)return R;let I={id:`nested-${j}-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:w,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:j}};return F.set(w,I),f(I),I},ge=[],Ye,Be=new Map,be=0,le="agent",He=!1,Gt=null,ft=null,vt=new Map,z=this.config.iterationDisplay??"separate";for(Ye=()=>{for(let w=0;w<ge.length;w++){let j=ge[w].payloadType,y=ge[w].payload;if(!He&&le!=="flow"&&typeof y.stepType=="string"&&(le="flow"),j==="reasoning_start"){let R=typeof y.id=="string"?y.id:null,I=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(R&&I){k.set(R,I),Oe(R,I,"reasoning");continue}let D=fe(y,!0)??`reason-${c()}`,O=te(D);O.reasoning=O.reasoning??{id:D,status:"streaming",chunks:[]},O.reasoning.startedAt=O.reasoning.startedAt??Te(y.startedAt??y.timestamp),O.reasoning.completedAt=void 0,O.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(O.reasoning.scope=y.scope),O.streaming=!0,O.reasoning.status="streaming",f(O)}else if(j==="reasoning_delta"){let R=typeof y.id=="string"?y.id:null;if(R&&k.has(R)&&F.has(R)){let H=F.get(R),X=y.reasoningText??y.text??y.delta??"";X&&y.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String(X)),f(H));continue}let I=fe(y,!1)??fe(y,!0)??`reason-${c()}`,D=te(I);D.reasoning=D.reasoning??{id:I,status:"streaming",chunks:[]},D.reasoning.startedAt=D.reasoning.startedAt??Te(y.startedAt??y.timestamp);let O=y.reasoningText??y.text??y.delta??"";if(O&&y.hidden!==!0){let H=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(H!==void 0){let X=We(I,H,String(O));D.reasoning.chunks=[X]}else D.reasoning.chunks.push(String(O))}if(D.reasoning.status=y.done?"complete":"streaming",y.done){D.reasoning.completedAt=Te(y.completedAt??y.timestamp);let H=D.reasoning.startedAt??Date.now();D.reasoning.durationMs=Math.max(0,(D.reasoning.completedAt??Date.now())-H)}D.streaming=D.reasoning.status!=="complete",f(D)}else if(j==="reasoning_complete"){let R=typeof y.id=="string"?y.id:null;if(R&&k.has(R)&&F.has(R)){let X=F.get(R);if(X.reasoning){let ie=typeof y.text=="string"?y.text:"";ie&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(ie),X.reasoning.status="complete",X.streaming=!1,f(X)}k.delete(R),F.delete(R);continue}let I=fe(y,!1)??fe(y,!0)??`reason-${c()}`,D=typeof y.text=="string"?y.text:"";!S.get(I)&&(D||y.scope==="loop")&&te(I);let O=S.get(I);if(O?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(O.reasoning.scope=y.scope),D&&O.reasoning.chunks.length===0&&O.reasoning.chunks.push(D),O.reasoning.status="complete",O.reasoning.completedAt=Te(y.completedAt??y.timestamp);let X=O.reasoning.startedAt??Date.now();O.reasoning.durationMs=Math.max(0,(O.reasoning.completedAt??Date.now())-X),O.streaming=!1,f(O)}let H=U(y);H&&G.byStep.delete(H)}else if(j==="tool_start"){b&&(b.streaming=!1,f(b),b=null),typeof y.iteration=="number"&&(be=y.iteration);let R=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??Ee(y,!0)??`tool-${c()}`,I=y.toolName??y.name;if(Ae(I)){Q.add(R);continue}de(Z(y),R);let D=Se(R),O=D.toolCall??{id:R,status:"pending"};O.name=I??O.name,O.status="running",y.parameters!==void 0?O.args=y.parameters:y.args!==void 0&&(O.args=y.args),O.startedAt=O.startedAt??Te(y.startedAt??y.timestamp),O.completedAt=void 0,O.durationMs=void 0,D.toolCall=O,D.streaming=!0,y.executionId&&(D.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(D)}else if(j==="tool_output_delta"){let R=Ee(y,!1)??Ee(y,!0)??`tool-${c()}`;if(Q.has(R))continue;let I=Se(R),D=I.toolCall??{id:R,status:"running"};D.startedAt=D.startedAt??Te(y.startedAt??y.timestamp);let O=y.text??y.delta??y.message??"";O&&(D.chunks=D.chunks??[],D.chunks.push(String(O))),D.status="running",I.toolCall=D,I.streaming=!0;let H=y.agentContext;(H||y.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(I)}else if(j==="tool_complete"){let R=Ee(y,!1)??Ee(y,!0)??`tool-${c()}`;if(Q.has(R)){Q.delete(R);continue}let I=Se(R),D=I.toolCall??{id:R,status:"running"};D.status="complete",y.result!==void 0&&(D.result=y.result),typeof y.duration=="number"&&(D.duration=y.duration),D.completedAt=Te(y.completedAt??y.timestamp);let O=y.duration??y.executionTime;if(typeof O=="number")D.durationMs=O;else{let ie=D.startedAt??Date.now();D.durationMs=Math.max(0,(D.completedAt??Date.now())-ie)}I.toolCall=D,I.streaming=!1;let H=y.agentContext;(H||y.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(I);let X=Z(y);X&&oe.byCall.delete(X)}else if(j==="await"&&y.toolName){let R=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,I=R??y.toolId??`local-${c()}`,D=Se(I),O=y.toolName,H=y.origin==="webmcp"&&!vo(O)?`webmcp:${O}`:O,X=vo(H),ie=D.toolCall??{id:I,status:"pending"};ie.name=H,ie.args=y.parameters,ie.status=X?"running":"complete",ie.chunks=ie.chunks??[],ie.startedAt=ie.startedAt??Te(y.startedAt??y.timestamp??y.awaitedAt),X?(ie.completedAt=void 0,ie.duration=void 0,ie.durationMs=void 0):ie.completedAt=ie.completedAt??ie.startedAt,D.toolCall=ie,D.streaming=!1,D.agentMetadata={...D.agentMetadata,executionId:y.executionId??D.agentMetadata?.executionId,awaitingLocalTool:!0,...R?{webMcpToolCallId:R}:{}},f(D)}else if(j==="text_start"){let R=typeof y.id=="string"?y.id:null,I=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(R&&I){k.set(R,I);continue}let D=b;D&&(le==="flow"?(Tt(D),bt=D):(D.streaming=!1,f(D)),b=null),W=typeof y.id=="string"?y.id:W,A=""}else if(j==="text_delta"){let R=typeof y.id=="string"?y.id:null,I=R?k.get(R):void 0;if(R&&I){let O=typeof y.delta=="string"?y.delta:"",H=(q.get(R)??"")+O;if(q.set(R,H),H.trim()==="")continue;let X=Oe(R,I);X.agentMetadata={...X.agentMetadata,executionId:y.executionId,parentToolId:I},Lt(X,H,O,void 0);continue}if(W=typeof y.id=="string"?y.id:W,le==="flow"){let O=typeof y.delta=="string"?y.delta:"";if(A+=O,A.trim()==="")continue;let H=ue();H.agentMetadata={executionId:y.executionId,iteration:y.iteration},Lt(H,A,O,void 0),C=H;continue}let D=ue();D.content+=y.delta??"",D.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:Gt??void 0,agentName:ft?.agentName},C=D,f(D)}else if(j==="text_complete"){let R=typeof y.id=="string"?y.id:null;if(R&&k.has(R)){let D=F.get(R);D&&Tt(D),k.delete(R),q.delete(R),F.delete(R);continue}let I=b;I&&(le==="flow"?(Tt(I),bt=I):((I.content??"")===""&&typeof y.text=="string"&&(I.content=y.text),I.streaming=!1,f(I)),b=null),W=null,A=""}else if(j==="step_complete"){let R=y.stepType,I=y.executionType;if(R==="tool"||I==="context")continue;if(y.success===!1){let D=y.error,O=typeof D=="string"&&D!==""?D:D!=null&&typeof D=="object"&&Reflect.has(D,"message")?String(D.message??"Step failed"):"Step failed";n({type:"error",error:new Error(O)});let H=b;H&&H.streaming&&(H.streaming=!1,f(H)),n({type:"status",status:"idle"});continue}{let D=bt;bt=null;let O=y.stopReason,H=y.result?.response;if(D)O&&(D.stopReason=O),H!=null?ot(D,H):D.streaming!==!1&&(Ue.delete(D.id),ke.delete(D.id),D.streaming=!1,f(D));else{let X=H!=null&&H!=="";if(X||O){let ie=ue();O&&(ie.stopReason=O),X?Tt(ie,H):(ie.streaming=!1,f(ie))}}continue}}else if(j==="execution_start")le=y.kind==="flow"?"flow":"agent",He=!0,le==="agent"&&(ft={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Te(y.startedAt)});else if(j==="turn_start"){let R=typeof y.iteration=="number"?y.iteration:be;if(R!==be){if(ft&&(ft.currentIteration=R),z==="separate"&&R>1){let I=b;I&&(I.streaming=!1,f(I),vt.set(R-1,I),b=null)}be=R}Gt=typeof y.id=="string"?y.id:null,C=null}else if(j==="tool_input_delta"){let R=y.toolCallId??oe.lastId;if(R){let I=V.get(R);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(y.delta??""),f(I))}}else{if(j==="tool_input_complete")continue;if(j==="turn_complete"){let R=y.stopReason,I=b??C;if(R&&I!==null){let D=y.id;(!D||I.agentMetadata?.turnId===D)&&(I.stopReason=R,f(I))}Gt===y.id&&(Gt=null)}else if(j==="media_start"){let R=String(y.id);Be.set(R,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(j==="media_delta"){let R=Be.get(String(y.id));R&&typeof y.delta=="string"&&R.parts.push(y.delta)}else if(j==="media_complete"){let R=String(y.id),I=Be.get(R);Be.delete(R);let D=(typeof y.mediaType=="string"?y.mediaType:void 0)??I?.mediaType??"application/octet-stream",O=typeof y.data=="string"?y.data:void 0,H=typeof y.url=="string"?y.url:I&&I.parts.length>0?I.parts.join(""):void 0,X=null;if(O)X={type:"media",data:O,mediaType:D};else if(H){let rt=D.toLowerCase();X={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:H,mediaType:D}}let ie=y.toolCallId??I?.toolCallId,Pe=X?[X]:[],we=[];for(let rt of Pe){if(!rt||typeof rt!="object")continue;let nt=rt,ze=typeof nt.type=="string"?nt.type:void 0,Qe=typeof nt.mediaType=="string"?nt.mediaType.toLowerCase():"",K=null,qe="";if(ze==="media"){let Ne=typeof nt.data=="string"?nt.data:void 0;if(!Ne)continue;qe=Qe.length>0?Qe:"application/octet-stream",K=`data:${qe};base64,${Ne}`}else if(ze==="image-url"){let Ne=typeof nt.url=="string"?nt.url:void 0;if(!Ne)continue;qe=Qe,K=Ne}else if(ze==="file-url"){let Ne=typeof nt.url=="string"?nt.url:void 0;if(!Ne)continue;qe=Qe,K=Ne}else continue;if(K)if(ze==="image-url"||qe.startsWith("image/"))we.push({type:"image",image:K,...qe.includes("/")?{mimeType:qe}:{}});else if(qe.startsWith("audio/"))we.push({type:"audio",audio:K,mimeType:qe});else if(qe.startsWith("video/"))we.push({type:"video",video:K,mimeType:qe});else{let Ne=qe||"application/octet-stream";we.push({type:"file",data:K,mimeType:Ne,filename:Oy(Ne)})}}if(we.length>0){let rt=c(),nt=ie,Qe={id:`agent-media-${typeof nt=="string"&&nt.length>0?`${nt}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:we,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:be}};f(Qe);let K=b;K&&(K.streaming=!1,f(K)),b=null,E.current=null}}else if(j==="execution_complete"){let R=y.kind??le;R==="agent"&&ft&&(ft.status=y.success?"complete":"error",ft.completedAt=Te(y.completedAt),ft.stopReason=y.stopReason);let I=b;I&&(R==="flow"&&I.streaming!==!1?Tt(I):(I.streaming=!1,f(I)),b=null),W=null,A="",bt=null,n({type:"status",status:"idle",terminal:!0})}else if(j==="execution_error"){let R=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(R)})}else if(j!=="ping"){if(j==="approval_start"){let R=y.approvalId??`approval-${c()}`,I={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:"pending",agentId:ft?.agentId??"virtual",executionId:y.executionId??ft?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(I)}else if(j==="step_await"&&y.awaitReason==="approval_required"){let R=y.approvalId??`approval-${c()}`,I={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:"pending",agentId:ft?.agentId??"virtual",executionId:y.executionId??ft?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(I)}else if(j==="approval_complete"){let R=y.approvalId;if(R){let D={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:y.decision??"approved",agentId:ft?.agentId??"virtual",executionId:y.executionId??ft?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(D)}}else if(j==="artifact_start"||j==="artifact_delta"||j==="artifact_update"||j==="artifact_complete"){if(j==="artifact_start"){let R=y.artifactType,I=String(y.id),D=typeof y.title=="string"?y.title:void 0,O=y.file,H;O&&typeof O=="object"&&!Array.isArray(O)&&typeof O.path=="string"&&typeof O.mimeType=="string"&&(H={path:O.path,mimeType:O.mimeType,...typeof O.language=="string"?{language:O.language}:{}}),n({type:"artifact_start",id:I,artifactType:R,title:D,component:typeof y.component=="string"?y.component:void 0,...H?{file:H}:{}});let X=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(ye.set(I,{markdown:"",title:D,file:H,...X?{props:X}:{}}),!xe.has(I)){xe.add(I);let ie=Bn(this.config.features?.artifacts,{artifactType:R,...H?{file:H}:{}}),Pe=typeof y.component=="string"?y.component:void 0,we={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ds(ie,{artifactId:I,title:D,artifactType:R,status:"streaming",...H?{file:H}:{},...Pe?{component:Pe}:{}})};me.set(I,we),f(we)}}else if(j==="artifact_delta"){let R=String(y.id),I=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:R,artDelta:I});let D=ye.get(R);D&&(D.markdown+=I)}else if(j==="artifact_update"){let R=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:R,component:typeof y.component=="string"?y.component:void 0});let I=ye.get(String(y.id));I&&(I.props={...I.props??{},...R})}else if(j==="artifact_complete"){let R=String(y.id);n({type:"artifact_complete",id:R});let I=me.get(R);if(I){I.streaming=!1;try{let D=JSON.parse(I.rawContent??"{}");if(D.props){D.props.status="complete";let O=ye.get(R);O?.markdown&&(D.props.markdown=O.markdown),O?.file&&(D.props.file=O.file),D.component==="PersonaArtifactInline"&&O?.props&&Object.keys(O.props).length>0&&(D.props.componentProps=O.props)}I.rawContent=JSON.stringify(D)}catch{}ye.delete(R),f(I),me.delete(R)}}}else if(j==="transcript_insert"){let R=y.message;if(!R||typeof R!="object")continue;let I=String(R.id??`msg-${c()}`),D=R.role,H={id:I,role:D==="user"?"user":D==="system"?"system":"assistant",content:typeof R.content=="string"?R.content:"",rawContent:typeof R.rawContent=="string"?R.rawContent:void 0,createdAt:typeof R.createdAt=="string"?R.createdAt:new Date().toISOString(),streaming:R.streaming===!0,...typeof R.variant=="string"?{variant:R.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let ie=JSON.parse(H.rawContent)?.props?.artifactId;typeof ie=="string"&&xe.add(ie)}catch{}b=null,E.current=null,Ue.delete(I),ke.delete(I)}else if(j==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let R=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(R)});let I=b;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(j==="step_error"||j==="dispatch_error"||j==="flow_error"){let R=null;if(y.error instanceof Error)R=y.error;else if(j==="dispatch_error"){let I=y.message??y.error;I!=null&&I!==""&&(R=new Error(String(I)))}else{let I=y.error;typeof I=="string"&&I!==""?R=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(R=new Error(String(I.message??I)))}if(R){n({type:"error",error:R});let I=b;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}ge.length=0};;){let{done:w,value:j}=await s.read();if(w)break;i+=a.decode(j,{stream:!0});let y=i.split(`
|
|
12
12
|
|
|
13
|
-
`);i=
|
|
14
|
-
`),W="message",G="",D=null;for(let We of M)We.startsWith("event:")?W=We.replace("event:","").trim():We.startsWith("data:")?G+=We.replace("data:","").trim():We.startsWith("id:")&&(D=We.slice(3).trim());let U=()=>{D!==null&&D!==""&&n({type:"cursor",id:D})};if(!G){U();continue}let Q;try{Q=JSON.parse(G)}catch(We){n({type:"error",error:We instanceof Error?We:new Error("Failed to parse chat stream payload")});continue}let Ge=W!=="message"?W:Q.type??"message";if(this.onSSEEvent?.(Ge,Q),this.parseSSEEvent){k.current=y;let We=await this.handleCustomSSEEvent(Q,n,k,f,c,L);if(k.current&&k.current!==y&&(y=k.current),We){U();continue}}pe.push({payloadType:Ge,payload:Q}),et(),U()}}et()}};function Mu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Hr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ao(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var li="[Image]";function Eu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ku(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ci(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Pu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function So(e){return{type:"text",text:e}}function Lu(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Ru(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Iu(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 Wu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],hy=["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"],Xn=[...Wu,...hy];function yy(e){return Wu.includes(e)||e.startsWith("image/")}function di(e){return yy(e.type)}async function Hu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;di(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Bu(e,t=Xn,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 by(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Du(e,t){let n=by(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"}dc();var Ou=16e3,vy=24e3,xy=4096,Cy=1380533830;function wy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Cy?new Uint8Array(e,44):new Uint8Array(e)}function Ay(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ds=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Ou,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:Ou});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Br(vy);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${Ay(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(p,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(xy,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),p=new Int16Array(d.length);for(let c=0;c<d.length;c++){let u=Math.max(-1,Math.min(1,d[c]));p[c]=u<0?u*32768:u*32767}o.send(p.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=wy(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var er=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function To(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ds(e.runtype);case"browser":if(!er.isSupported())throw new Error("Browser speech recognition not supported");return new er(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 pi(e){if(e?.type==="custom"&&e.custom)return To({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return To({type:"runtype",runtype:e.runtype});if(er.isSupported())return To({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Os(e){try{return pi(e),!0}catch{return!1}}function Dr(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Mo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Dr(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var tr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function pc(e){if(!e)return"";let t=Sy(e);return Nu(t!==null?t:e)}function Sy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Nu(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
|
+
`);i=y.pop()??"";for(let R of y){let I=R.split(`
|
|
14
|
+
`),D="message",O="",H=null;for(let we of I)we.startsWith("event:")?D=we.replace("event:","").trim():we.startsWith("data:")?O+=we.replace("data:","").trim():we.startsWith("id:")&&(H=we.slice(3).trim());let X=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!O){X();continue}let ie;try{ie=JSON.parse(O)}catch(we){n({type:"error",error:we instanceof Error?we:new Error("Failed to parse chat stream payload")});continue}let Pe=D!=="message"?D:ie.type??"message";if(this.onSSEEvent?.(Pe,ie),this.parseSSEEvent){E.current=b;let we=await this.handleCustomSSEEvent(ie,n,E,f,c,L);if(E.current&&E.current!==b&&(b=E.current),we){X();continue}}ge.push({payloadType:Pe,payload:ie}),Ye(),X()}}Ye()}};function qu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Eo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var gi="[Image]";function Vu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ku(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function fi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Gu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ko(e){return{type:"text",text:e}}function Ju(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Xu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Yu(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 Qu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],_y=["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"],Zn=[...Qu,..._y];function $y(e){return Qu.includes(e)||e.startsWith("image/")}function mi(e){return $y(e.type)}async function Zu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;mi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function eg(e,t=Zn,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 jy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function tg(e,t){let n=jy(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"}hc();var ng=16e3,Uy=24e3,zy=4096,qy=1380533830;function Vy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===qy?new Uint8Array(e,44):new Uint8Array(e)}function Ky(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Us=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:ng,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:ng});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new _r(Uy);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${Ky(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(p,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let v=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${v}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(zy,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),p=new Int16Array(d.length);for(let c=0;c<d.length;c++){let u=Math.max(-1,Math.min(1,d[c]));p[c]=u<0?u*32768:u*32767}o.send(p.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Vy(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var sr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Po(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Us(e.runtype);case"browser":if(!sr.isSupported())throw new Error("Browser speech recognition not supported");return new sr(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function hi(e){if(e?.type==="custom"&&e.custom)return Po({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Po({type:"runtype",runtype:e.runtype});if(sr.isSupported())return Po({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zs(e){try{return hi(e),!0}catch{return!1}}function $r(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Lo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):$r(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ar=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function yc(e){if(!e)return"";let t=Gy(e);return og(t!==null?t:e)}function Gy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function og(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
16
|
-
`),t.trim()}var
|
|
16
|
+
`),t.trim()}var lg=null;var bc=()=>lg?lg():Promise.resolve().then(()=>(ig(),ag));var Zy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function eb(e,t){return Zy.some(n=>e[n]!==t[n])}function vc(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]}),Vu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ku=e=>ho(e)||e===Tn,Or=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new tr(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(ho(n.name)||n.name===Tn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Zo(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||uc().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Os(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Mo.isSupported()?new Mo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return uc().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:d})=>{let p=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=To(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=d.id}if(i){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=d.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!Ly(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Zo(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:p=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?Hr():n==="assistant"?Ao():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:p,sequence:c,streaming:u=!1,voiceProcessing:b,rawContent:f}=o,C={id:d??(r==="user"?Hr():r==="assistant"?Ao():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...b!==void 0&&{voiceProcessing:b},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var qs=e=>({isError:!0,content:[{type:"text",text:e}]}),pg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ug=e=>vo(e)||e===En,jr=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ar(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(vo(n.name)||n.name===En&&To(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new rr(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||bc().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return zs(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Lo.isSupported()?new Lo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return bc().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:d})=>{let p=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Po(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=d.id}if(i){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=d.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!eb(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new rr(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:p=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?Fr():n==="assistant"?Eo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:p,sequence:c,streaming:u=!1,voiceProcessing:v,rawContent:f}=o,C={id:d??(r==="user"?Fr():r==="assistant"?Eo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...v!==void 0&&{voiceProcessing:v},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
20
|
`),a=[s,n].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(i){let p=[];s&&p.push(So(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(So(a)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Hr(),s=Ao();this.activeAssistantMessageId=null;let a=n?.contentParts&&ci(n.contentParts)?li:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let c=this.messages.find(u=>u.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:d.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let b=fc(c,this.config.errorMessage);if(b){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=Ao();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=fc(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let c;if(p?c=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let b=await c.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};p.forEach((u,b)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let y=c[f],C=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${i}-${b}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Tn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async d=>{let p=d.toolCall?.name,c=d.toolCall?.id;if(!p||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(u),o.push(u);let b=this.markWebMcpToolRunning(d),f=d.agentMetadata?.webMcpToolCallId??p;if(p===Tn)return{dedupeKey:u,resumeKey:f,output:rc(),toolMessage:d,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let C=this.client.executeWebMcpToolCall(p,d.toolCall?.args,y.signal),k;if(!C)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await C}catch(L){let H=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return H||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(d,Ns(H?"Aborted by cancel()":Vu(L)),b),this.webMcpInflightKeys.delete(u),null}return y.signal.aborted?(this.markWebMcpToolComplete(d,Ns("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:k,toolMessage:d,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let d={};for(let c of i)d[c.resumeKey]=c.output;let p=await this.client.resumeFlow(t,d,{signal:s.signal});if(!p.ok){let c=await p.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${p.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Tn?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,Ns("Aborted by cancel()"),c.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let p=o===Tn,c=t.toolCall?.args,u=p?null:this.client.executeWebMcpToolCall(o,c,d),b="execute",f=a;try{let y;if(p?y=rc():u?y=await u:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ns("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,y,a,f,p?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(y){let C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||C||d.aborted)&&this.markWebMcpToolComplete(t,Ns(C||d.aborted?"Aborted by cancel()":Vu(y)),a),C||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=In(this.config.features?.artifacts,t),r=ks(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=In(this.config.features?.artifacts,n),s=ks(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(qu(),zu)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>fc(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Ao(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=pc(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Dr(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=pc(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(i&&Ku(i)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${d}:${p}`,u=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,y=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&f!==void 0&&Ku(f)&&r.toolCall?.status==="complete";(u||b||y)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var S=require("lucide"),Ry={activity:S.Activity,"arrow-down":S.ArrowDown,"arrow-up":S.ArrowUp,"arrow-up-right":S.ArrowUpRight,bot:S.Bot,"chevron-down":S.ChevronDown,"chevron-up":S.ChevronUp,"chevron-right":S.ChevronRight,"chevron-left":S.ChevronLeft,check:S.Check,clipboard:S.Clipboard,"clipboard-copy":S.ClipboardCopy,"code-xml":S.CodeXml,copy:S.Copy,file:S.File,"file-code":S.FileCode,"file-spreadsheet":S.FileSpreadsheet,"file-text":S.FileText,"image-plus":S.ImagePlus,loader:S.Loader,"loader-circle":S.LoaderCircle,mic:S.Mic,paperclip:S.Paperclip,"refresh-cw":S.RefreshCw,search:S.Search,send:S.Send,"shield-alert":S.ShieldAlert,"shield-check":S.ShieldCheck,"shield-x":S.ShieldX,square:S.Square,"thumbs-down":S.ThumbsDown,"thumbs-up":S.ThumbsUp,upload:S.Upload,"volume-2":S.Volume2,x:S.X,user:S.User,mail:S.Mail,phone:S.Phone,calendar:S.Calendar,clock:S.Clock,building:S.Building,"map-pin":S.MapPin,lock:S.Lock,key:S.Key,"credit-card":S.CreditCard,"at-sign":S.AtSign,hash:S.Hash,globe:S.Globe,link:S.Link,"circle-check":S.CircleCheck,"circle-x":S.CircleX,"triangle-alert":S.TriangleAlert,info:S.Info,ban:S.Ban,shield:S.Shield,"arrow-left":S.ArrowLeft,"arrow-right":S.ArrowRight,"external-link":S.ExternalLink,ellipsis:S.Ellipsis,"ellipsis-vertical":S.EllipsisVertical,menu:S.Menu,house:S.House,plus:S.Plus,minus:S.Minus,pencil:S.Pencil,trash:S.Trash,"trash-2":S.Trash2,save:S.Save,download:S.Download,share:S.Share,funnel:S.Funnel,settings:S.Settings,"rotate-cw":S.RotateCw,maximize:S.Maximize,minimize:S.Minimize,"shopping-cart":S.ShoppingCart,"shopping-bag":S.ShoppingBag,package:S.Package,truck:S.Truck,tag:S.Tag,gift:S.Gift,receipt:S.Receipt,wallet:S.Wallet,store:S.Store,"dollar-sign":S.DollarSign,percent:S.Percent,play:S.Play,pause:S.Pause,"volume-x":S.VolumeX,camera:S.Camera,image:S.Image,film:S.Film,headphones:S.Headphones,"message-circle":S.MessageCircle,"message-square":S.MessageSquare,bell:S.Bell,heart:S.Heart,star:S.Star,eye:S.Eye,"eye-off":S.EyeOff,bookmark:S.Bookmark,"calendar-days":S.CalendarDays,history:S.History,timer:S.Timer,folder:S.Folder,"folder-open":S.FolderOpen,files:S.Files,sparkles:S.Sparkles,zap:S.Zap,sun:S.Sun,moon:S.Moon,flag:S.Flag,monitor:S.Monitor,smartphone:S.Smartphone},re=(e,t=24,n="currentColor",o=2)=>{let r=Ry[e];return r?Iy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Iy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([p,c])=>{p!=="stroke"&&d.setAttribute(p,String(c))}),r.appendChild(d)}),r}var gi={allowedTypes:Xn,maxFileSize:10*1024*1024,maxFiles:4};function Wy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Hy(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 nr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??gi.allowedTypes,maxFileSize:t.maxFileSize??gi.maxFileSize,maxFiles:t.maxFiles??gi.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:gi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Bu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Hu(n),s=di(n)?URL.createObjectURL(n):null,a={id:Wy(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=di(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Hy(t.file.type),d=re(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let p=m("span");p.textContent=Du(t.file.type,t.file.name),p.style.fontSize="8px",p.style.fontWeight="600",p.style.color="var(--persona-muted, #6b7280)",p.style.textTransform="uppercase",p.style.lineHeight="1",a.appendChild(p),o.appendChild(a)}let r=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=re("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Gu=/\s/;function By(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
23
|
-
`:o===""||
|
|
24
|
-
`||a==="\uFFFC"||!r&&
|
|
25
|
-
`).some(q=>q.startsWith(
|
|
26
|
-
`)[0]).startsWith(P.trigger):!1),s=(E,P)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${E}`,{detail:P}))}catch{}},a=Fe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,d=null,p=e.textarea,c=null,u=null,b=null,f=null,y=()=>{if(i)return Promise.resolve(i);if(d)return d;let E=yc().then(P=>(i=P.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:H,emit:s}),i)).catch(P=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",P),d===E&&(d=null),null));return d=E,E},C=()=>{ef().then(E=>{let P=E.mountInlineComposer({textarea:e.textarea,renderToken:q=>Fs(q,{render:t.renderMentionToken}),onMentionRemoved:q=>i?.untrackMention(q)});c=P.input,u=P.destroy;let _=p;_.replaceWith(P.element),p=P.element,f={next:P.element,prev:_},b?.(P.element,_),i?i.rebindComposer(P.input):d&&d.then(q=>q?.rebindComposer(P.input))}).catch(E=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",E)})};t.display==="inline"&&C();let k=[],L=new Map;for(let E of n){if(!E.showButton)continue;let P=Zu({config:{...t,buttonIconName:E.buttonIconName,buttonTooltipText:E.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{y().then(_=>_?.openMenu(E.trigger))}});k.push(P),L.set(E.trigger,P.button)}let H=(E,P,_)=>{let q=L.get(P);q&&(q.setAttribute("aria-expanded",E?"true":"false"),E?q.setAttribute("aria-controls",_):q.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(E=>E.wrapper),contextRow:a,handleInput:E=>{if(i){i.handleInput();return}if(!Xu(E))return;let P=p,_=P.selectionStart??0;Ju(P.value,_,n)&&y().then(q=>q?.handleInput())},handleKeydown:E=>{if(i?.isMenuOpen())return i.handleKeydown(E);if(E.key==="Backspace"&&i?.hasMentions()&&!f){let P=p,_=P.selectionStart===0&&P.selectionEnd===0;if((P.value.length===0||_)&&i.removeLastChip())return E.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async E=>r(E)?(i??await y())?.dispatchInlineCommand(E)??null:null,clear:()=>i?.clear(),prefetch:()=>{yc().catch(()=>{})},onComposerSwap:E=>{b=E,f&&E(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let E of k)E.wrapper.remove();a.remove()}}}var nf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _s(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];nf(s)&&nf(r)?n[o]=_s(s,r):n[o]=r}return n}var ln="min(440px, calc(100vw - 24px))",hi="440px",jy={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:ln,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:jy,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function of(e,t){if(!(!e&&!t))return e?t?_s(e,t):e:t}function Nr(e){return e?{...it,...e,theme:of(it.theme,e.theme),darkTheme:of(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,s=it.features?.scrollBehavior,a=e.features?.scrollBehavior,i=it.features?.streamAnimation,d=e.features?.streamAnimation,p=it.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},y=i===void 0&&d===void 0?void 0:{...i,...d},C=p===void 0&&c===void 0?void 0:{...p,...c,styles:{...p?.styles,...c?.styles}};return{...it.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...y!==void 0?{streamAnimation:y}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}var yi="16px",bi="transparent",bc={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"}},vc={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"}},xc={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:ln,maxWidth:hi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:yi,canvasBackground:bi},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Jt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Jt(e,o):o}function vi(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Jt(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Cc(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 rf(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=rf(s,r):n[o]=r}return n}function Uy(e,t){return t?rf(e,t):e}function $s(e,t={}){let n={palette:bc,semantic:vc,components:xc},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Uy(n.components,e?.components)};if(t.validate!==!1){let r=Cc(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function xi(e){let t=vi(e),n={};for(let[w,z]of Object.entries(t)){let V=w.replace(/\./g,"-");n[`--persona-${V}`]=z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??yi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??bi,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);let d=n["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(n["--persona-md-prose-font-family"]=d),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let p=e.components,c=p?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=p?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let b=p?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let f=p?.artifact;if(f?.toolbar){let w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Jt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let z=Jt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=z}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Jt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Jt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Jt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Jt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Jt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let y=p?.code;y&&(y.keywordColor&&(n["--persona-code-keyword-color"]=y.keywordColor),y.stringColor&&(n["--persona-code-string-color"]=y.stringColor),y.commentColor&&(n["--persona-code-comment-color"]=y.commentColor),y.numberColor&&(n["--persona-code-number-color"]=y.numberColor),y.tagColor&&(n["--persona-code-tag-color"]=y.tagColor),y.attrColor&&(n["--persona-code-attr-color"]=y.attrColor),y.propertyColor&&(n["--persona-code-property-color"]=y.propertyColor),y.lineNumberColor&&(n["--persona-code-line-number-color"]=y.lineNumberColor),y.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=y.gutterBorderColor),y.background&&(n["--persona-code-bg"]=Jt(e,y.background)??y.background));let C=n["--persona-surface"],k=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",H=n["--persona-palette-colors-gray-200"]??"#e5e7eb",E=n["--persona-palette-colors-gray-300"]??"#d1d5db",P=!k||k===C,_=P?L:k,q=P?H:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??q,P&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??E),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var sf={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var zy={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"}}},af=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},js=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",qy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":js()},Ci=e=>qy(e),Vy=e=>$s(e),Ky=e=>$s({...e,palette:{...e?.palette,colors:{...zy.colors,...e?.palette?.colors}}},{validate:!1}),Eo=e=>{let t=Ci(e),n=af(e?.theme),o=af(e?.darkTheme);return t==="dark"?Ky(_s(n??{},o??{})):Vy(n)},Gy=e=>xi(e),or=(e,t)=>{let n=Eo(t),o=Gy(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Ci(t))},Fr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(js())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(js());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Wn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function lf(e){let t=Wn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function wi(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
22
|
+
`),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(i){let p=[];s&&p.push(ko(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(ko(a)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Fr(),s=Eo();this.activeAssistantMessageId=null;let a=n?.contentParts&&fi(n.contentParts)?gi:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let c=this.messages.find(u=>u.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:d.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let v=vc(c,this.config.errorMessage);if(v){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:v,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=Eo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=vc(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let c;if(p?c=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let v=await c.json().catch(()=>null);throw new Error(v?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let v=typeof u[0]?.question=="string"?u[0].question:"";v&&(a={[v]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,v])=>`${u}: ${Array.isArray(v)?v.join(", "):v}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};p.forEach((u,v)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let b=c[f],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${i}-${v}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${v}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==En?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async d=>{let p=d.toolCall?.name,c=d.toolCall?.id;if(!p||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(u),o.push(u);let v=this.markWebMcpToolRunning(d),f=d.agentMetadata?.webMcpToolCallId??p;if(p===En)return{dedupeKey:u,resumeKey:f,output:dc(),toolMessage:d,startedAt:v,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let C=this.client.executeWebMcpToolCall(p,d.toolCall?.args,b.signal),E;if(!C)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await C}catch(L){let W=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return W||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(d,qs(W?"Aborted by cancel()":pg(L)),v),this.webMcpInflightKeys.delete(u),null}return b.signal.aborted?(this.markWebMcpToolComplete(d,qs("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,toolMessage:d,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let d={};for(let c of i)d[c.resumeKey]=c.output;let p=await this.client.resumeFlow(t,d,{signal:s.signal});if(!p.ok){let c=await p.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${p.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===En?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,qs("Aborted by cancel()"),c.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(b)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let p=o===En,c=t.toolCall?.args,u=p?null:this.client.executeWebMcpToolCall(o,c,d),v="execute",f=a;try{let b;if(p?b=dc():u?b=await u:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,qs("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;v="resume",await this.resumeWithToolOutput(n,C,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,b,a,f,p?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(b){let C=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(v==="execute"||C||d.aborted)&&this.markWebMcpToolComplete(t,qs(C||d.aborted?"Aborted by cancel()":pg(b)),a),C||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Bn(this.config.features?.artifacts,t),r=Ds(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Bn(this.config.features?.artifacts,n),s=Ds(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(dg(),cg)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>vc(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Eo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=yc(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return $r(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=yc(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(i&&ug(i)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${d}:${p}`,u=this.webMcpInflightKeys.has(c),v=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&f!==void 0&&ug(f)&&r.toolCall?.status==="complete";(u||v||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var T=require("lucide"),tb={activity:T.Activity,"arrow-down":T.ArrowDown,"arrow-up":T.ArrowUp,"arrow-up-right":T.ArrowUpRight,bot:T.Bot,"chevron-down":T.ChevronDown,"chevron-up":T.ChevronUp,"chevron-right":T.ChevronRight,"chevron-left":T.ChevronLeft,check:T.Check,clipboard:T.Clipboard,"clipboard-copy":T.ClipboardCopy,"code-xml":T.CodeXml,copy:T.Copy,file:T.File,"file-code":T.FileCode,"file-spreadsheet":T.FileSpreadsheet,"file-text":T.FileText,"image-plus":T.ImagePlus,loader:T.Loader,"loader-circle":T.LoaderCircle,mic:T.Mic,paperclip:T.Paperclip,"refresh-cw":T.RefreshCw,search:T.Search,send:T.Send,"shield-alert":T.ShieldAlert,"shield-check":T.ShieldCheck,"shield-x":T.ShieldX,square:T.Square,"thumbs-down":T.ThumbsDown,"thumbs-up":T.ThumbsUp,upload:T.Upload,"volume-2":T.Volume2,x:T.X,user:T.User,mail:T.Mail,phone:T.Phone,calendar:T.Calendar,clock:T.Clock,building:T.Building,"map-pin":T.MapPin,lock:T.Lock,key:T.Key,"credit-card":T.CreditCard,"at-sign":T.AtSign,hash:T.Hash,globe:T.Globe,link:T.Link,"circle-check":T.CircleCheck,"circle-x":T.CircleX,"triangle-alert":T.TriangleAlert,info:T.Info,ban:T.Ban,shield:T.Shield,"arrow-left":T.ArrowLeft,"arrow-right":T.ArrowRight,"external-link":T.ExternalLink,ellipsis:T.Ellipsis,"ellipsis-vertical":T.EllipsisVertical,menu:T.Menu,house:T.House,plus:T.Plus,minus:T.Minus,pencil:T.Pencil,"pen-line":T.PenLine,trash:T.Trash,"trash-2":T.Trash2,save:T.Save,download:T.Download,share:T.Share,funnel:T.Funnel,settings:T.Settings,"rotate-cw":T.RotateCw,maximize:T.Maximize,minimize:T.Minimize,"shopping-cart":T.ShoppingCart,"shopping-bag":T.ShoppingBag,package:T.Package,truck:T.Truck,tag:T.Tag,gift:T.Gift,receipt:T.Receipt,wallet:T.Wallet,store:T.Store,"dollar-sign":T.DollarSign,percent:T.Percent,play:T.Play,pause:T.Pause,"volume-x":T.VolumeX,camera:T.Camera,image:T.Image,film:T.Film,headphones:T.Headphones,"message-circle":T.MessageCircle,"message-square":T.MessageSquare,bell:T.Bell,heart:T.Heart,star:T.Star,eye:T.Eye,"eye-off":T.EyeOff,bookmark:T.Bookmark,"calendar-days":T.CalendarDays,history:T.History,timer:T.Timer,folder:T.Folder,"folder-open":T.FolderOpen,files:T.Files,"chart-column":T.ChartColumn,sparkles:T.Sparkles,zap:T.Zap,sun:T.Sun,moon:T.Moon,flag:T.Flag,lightbulb:T.Lightbulb,monitor:T.Monitor,smartphone:T.Smartphone},re=(e,t=24,n="currentColor",o=2)=>{let r=tb[e];return r?nb(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function nb(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([p,c])=>{p!=="stroke"&&d.setAttribute(p,String(c))}),r.appendChild(d)}),r}var vi={allowedTypes:Zn,maxFileSize:10*1024*1024,maxFiles:4};function ob(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function rb(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 ir=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??vi.allowedTypes,maxFileSize:t.maxFileSize??vi.maxFileSize,maxFiles:t.maxFiles??vi.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:vi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=eg(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Zu(n),s=mi(n)?URL.createObjectURL(n):null,a={id:ob(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=mi(t.file),o=h("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=h("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=rb(t.file.type),d=re(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let p=h("span");p.textContent=tg(t.file.type,t.file.name),p.style.fontSize="8px",p.style.fontWeight="600",p.style.color="var(--persona-muted, #6b7280)",p.style.textTransform="uppercase",p.style.lineHeight="1",a.appendChild(p),o.appendChild(a)}let r=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=re("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var gg=/\s/;function sb(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
23
|
+
`:o===""||gg.test(o)}function ab(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return sb(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
|
|
24
|
+
`||a==="\uFFFC"||!r&&gg.test(a))return null;s--}return null}function fg(e,t,n){for(let o of n){let r=ab(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function mg(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function hg(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Kt=1e5,xi=Kt+1;var ib=8,lb=8,xc=10,Cc=new WeakMap,yg=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,cb=e=>{let t=e.getRootNode?.();return yg(t)?t:e.ownerDocument.body},wc=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function $t(e){Cc.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=ib,viewportPadding:a=lb}=e,i=()=>t.ownerDocument,d=()=>i().defaultView??window,p=null,c=null,u=null,v=!1,f=!1,b=!1,C=()=>(typeof o=="function"?o():o).trim(),E=()=>{u?.(),u=null,p?.remove(),p=null,c=null},L=()=>{if(!p)return;let oe=i(),N=d(),U=t.getBoundingClientRect(),Z=p.getBoundingClientRect(),he=oe.documentElement.clientWidth||N.innerWidth,ve=oe.documentElement.clientHeight||N.innerHeight,ue=he-a-Z.width,ne=U.left+U.width/2-Z.width/2,fe=wc(ne,a,ue),te=U.top-a,de=ve-a-U.bottom,Q=Z.height+s,me=te>=Q||te>=de?"top":"bottom",xe=me==="top"?U.top-s-Z.height:U.bottom+s,ye=ve-a-Z.height,Ae=wc(xe,a,ye),Ee=U.left+U.width/2,Se=Math.max(xc,Z.width-xc),Te=wc(Ee-fe,xc,Se);p.dataset.placement=me,p.style.left=`${fe}px`,p.style.top=`${Ae}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${Te}px`)},W=()=>{if(b||!r||p||!t.isConnected)return;let oe=C(),N=cb(t);if(!oe||!N)return;let U=i(),Z=d();p=U.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(xi),c=U.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=oe,p.appendChild(c);let he=U.createElement("span");he.className="persona-control-tooltip__arrow",p.appendChild(he),N.appendChild(p),L(),p.dataset.state="open";let ve=()=>{if(!t.isConnected){E();return}c&&(c.textContent=C()),L()};Z.addEventListener("scroll",ve,!0),Z.addEventListener("resize",ve);let ue=t.getRootNode(),ne=yg(ue)?ue:U.documentElement,fe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||E()});fe?.observe(ne,{childList:!0,subtree:!0}),u=()=>{Z.removeEventListener("scroll",ve,!0),Z.removeEventListener("resize",ve),fe?.disconnect()}},A=()=>{v||f?W():E()},k=()=>{let oe=d();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(v=!0,A())},F=()=>{v=!1,A()},q=()=>{f=!0,A()},S=()=>{f=!1,A()},V=oe=>{oe.key==="Escape"&&(v=!1,f=!1,E())};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",F),t.addEventListener("focus",q),t.addEventListener("blur",S),t.addEventListener("keydown",V);let G={get isOpen(){return p!==null},show:W,hide:E,reposition:L,destroy:()=>{b||(b=!0,E(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",F),t.removeEventListener("focus",q),t.removeEventListener("blur",S),t.removeEventListener("keydown",V),Cc.delete(t))}};return Cc.set(t,G),G}function bg(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",d=h("div","persona-send-button-wrapper"),p=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=re(a,s,"currentColor",1.5);return c?p.appendChild(c):p.textContent="+",p.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),d.appendChild(p),$t({anchor:p,trigger:d,text:()=>p.getAttribute("aria-label")??i}),{button:p,wrapper:d}}var{setLoader:hA,load:db}=Rr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Ac=db;var{setLoader:vA,load:pb}=Rr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var vg=pb;function Vs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ie("span",{className:Gn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=re(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=h("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ie("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function xg(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=hg(t).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(k=>typeof k.matchCommand=="function")),r=A=>o.some(k=>k.trigger?k.position==="line-start"?A.split(`
|
|
25
|
+
`).some(q=>q.startsWith(k.trigger)):(k.position==="anywhere"?A:A.split(`
|
|
26
|
+
`)[0]).startsWith(k.trigger):!1),s=(A,k)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:k}))}catch{}},a=Ie("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,d=null,p=e.textarea,c=null,u=null,v=null,f=null,b=()=>{if(i)return Promise.resolve(i);if(d)return d;let A=Ac().then(k=>(i=k.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:W,emit:s}),i)).catch(k=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",k),d===A&&(d=null),null));return d=A,A},C=()=>{vg().then(A=>{let k=A.mountInlineComposer({textarea:e.textarea,renderToken:q=>Vs(q,{render:t.renderMentionToken}),onMentionRemoved:q=>i?.untrackMention(q)});c=k.input,u=k.destroy;let F=p;F.replaceWith(k.element),p=k.element,f={next:k.element,prev:F},v?.(k.element,F),i?i.rebindComposer(k.input):d&&d.then(q=>q?.rebindComposer(k.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&C();let E=[],L=new Map;for(let A of n){if(!A.showButton)continue;let k=bg({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(F=>F?.openMenu(A.trigger))}});E.push(k),L.set(A.trigger,k.button)}let W=(A,k,F)=>{let q=L.get(k);q&&(q.setAttribute("aria-expanded",A?"true":"false"),A?q.setAttribute("aria-controls",F):q.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:a,handleInput:A=>{if(i){i.handleInput();return}if(!mg(A))return;let k=p,F=k.selectionStart??0;fg(k.value,F,n)&&b().then(q=>q?.handleInput())},handleKeydown:A=>{if(i?.isMenuOpen())return i.handleKeydown(A);if(A.key==="Backspace"&&i?.hasMentions()&&!f){let k=p,F=k.selectionStart===0&&k.selectionEnd===0;if((k.value.length===0||F)&&i.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(i??await b())?.dispatchInlineCommand(A)??null:null,clear:()=>i?.clear(),prefetch:()=>{Ac().catch(()=>{})},onComposerSwap:A=>{v=A,f&&A(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let A of E)A.wrapper.remove();a.remove()}}}var Cg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ks(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Cg(s)&&Cg(r)?n[o]=Ks(s,r):n[o]=r}return n}var dn="min(440px, calc(100vw - 24px))",Ci="440px",ub={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:dn,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)"},at={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:ub,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function wg(e,t){if(!(!e&&!t))return e?t?Ks(e,t):e:t}function Ur(e){return e?{...at,...e,theme:wg(at.theme,e.theme),darkTheme:wg(at.darkTheme,e.darkTheme),launcher:{...at.launcher,...e.launcher,dock:{...at.launcher?.dock,...e.launcher?.dock},clearChat:{...at.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...at.copy,...e.copy},sendButton:{...at.sendButton,...e.sendButton},statusIndicator:{...at.statusIndicator,...e.statusIndicator},voiceRecognition:{...at.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=at.features?.artifacts,n=e.features?.artifacts,o=at.features?.scrollToBottom,r=e.features?.scrollToBottom,s=at.features?.scrollBehavior,a=e.features?.scrollBehavior,i=at.features?.streamAnimation,d=e.features?.streamAnimation,p=at.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},v=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},b=i===void 0&&d===void 0?void 0:{...i,...d},C=p===void 0&&c===void 0?void 0:{...p,...c,styles:{...p?.styles,...c?.styles}};return{...at.features,...e.features,...v!==void 0?{scrollToBottom:v}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...b!==void 0?{streamAnimation:b}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...at.layout,...e.layout,header:{...at.layout?.header,...e.layout?.header},messages:{...at.layout?.messages,...e.layout?.messages,avatar:{...at.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...e.layout?.slots}},markdown:{...at.markdown,...e.markdown,options:{...at.markdown?.options,...e.markdown?.options}},messageActions:{...at.messageActions,...e.messageActions}}:at}var wi="16px",Ai="transparent",Sc={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Tc={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Mc={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",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:dn,maxWidth:Ci,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:wi,canvasBackground:Ai},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Yt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Yt(e,o):o}function Si(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Yt(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Ec(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 Ag(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Ag(s,r):n[o]=r}return n}function gb(e,t){return t?Ag(e,t):e}function Gs(e,t={}){let n={palette:Sc,semantic:Tc,components:Mc},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:gb(n.components,e?.components)};if(t.validate!==!1){let r=Ec(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Ti(e){let t=Si(e),n={};for(let[S,V]of Object.entries(t)){let G=S.replace(/\./g,"-");n[`--persona-${G}`]=V.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??wi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ai,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);let d=n["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(n["--persona-md-prose-font-family"]=d),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let p=e.components,c=p?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=p?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let v=p?.toggleGroup;v&&(v.gap&&(n["--persona-toggle-group-gap"]=v.gap),v.borderRadius&&(n["--persona-toggle-group-radius"]=v.borderRadius));let f=p?.artifact;if(f?.toolbar){let S=f.toolbar;S.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=S.toggleGroupPadding),S.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=S.toggleGroupBorder),S.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=S.toggleGroupBorderRadius),S.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Yt(e,S.toggleGroupBackground)??S.toggleGroupBackground),S.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??S.copyMenuBackground),S.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??S.copyMenuBorder),S.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??S.copyMenuShadow),S.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??S.copyMenuItemHoverBackground),S.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(f?.tab){let S=f.tab;S.background&&(n["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(n["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(n["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(n["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(n["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(n["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(n["--persona-artifact-tab-list-padding"]=S.listPadding)}if(f?.pane){let S=f.pane;if(S.toolbarBackground){let V=Yt(e,S.toolbarBackground)??S.toolbarBackground;n["--persona-artifact-toolbar-bg"]=V}}if(f?.card){let S=f.card;S.background&&(n["--persona-artifact-card-bg"]=S.background),S.border&&(n["--persona-artifact-card-border"]=S.border),S.borderRadius&&(n["--persona-artifact-card-radius"]=S.borderRadius),S.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=S.hoverBackground),S.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=S.hoverBorderColor)}if(f?.inline){let S=f.inline;S.background&&(n["--persona-artifact-inline-bg"]=Yt(e,S.background)??S.background),S.border&&(n["--persona-artifact-inline-border"]=S.border),S.borderRadius&&(n["--persona-artifact-inline-radius"]=S.borderRadius),S.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Yt(e,S.chromeBackground)??S.chromeBackground),S.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Yt(e,S.chromeBorder)??S.chromeBorder),S.titleColor&&(n["--persona-artifact-inline-title-color"]=Yt(e,S.titleColor)??S.titleColor),S.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Yt(e,S.mutedColor)??S.mutedColor),S.frameHeight&&(n["--persona-artifact-inline-frame-height"]=S.frameHeight)}let b=p?.code;b&&(b.keywordColor&&(n["--persona-code-keyword-color"]=b.keywordColor),b.stringColor&&(n["--persona-code-string-color"]=b.stringColor),b.commentColor&&(n["--persona-code-comment-color"]=b.commentColor),b.numberColor&&(n["--persona-code-number-color"]=b.numberColor),b.tagColor&&(n["--persona-code-tag-color"]=b.tagColor),b.attrColor&&(n["--persona-code-attr-color"]=b.attrColor),b.propertyColor&&(n["--persona-code-property-color"]=b.propertyColor),b.lineNumberColor&&(n["--persona-code-line-number-color"]=b.lineNumberColor),b.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=b.gutterBorderColor),b.background&&(n["--persona-code-bg"]=Yt(e,b.background)??b.background));let C=n["--persona-surface"],E=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",k=!E||E===C,F=k?L:E,q=k?W:E;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??F,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??q,k&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??F,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??F,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??F,n}var Sg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var fb={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"}}},Tg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Js=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",mb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Js()},Mi=e=>mb(e),hb=e=>Gs(e),yb=e=>Gs({...e,palette:{...e?.palette,colors:{...fb.colors,...e?.palette?.colors}}},{validate:!1}),Ro=e=>{let t=Mi(e),n=Tg(e?.theme),o=Tg(e?.darkTheme);return t==="dark"?yb(Ks(n??{},o??{})):hb(n)},bb=e=>Ti(e),lr=(e,t)=>{let n=Ro(t),o=bb(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Mi(t))},zr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Js())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Js());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Dn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Mg(e){let t=Dn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ei(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
27
27
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
28
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
29
|
-
`).length,f=e.artifactType==="markdown"?e.file:void 0,
|
|
28
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Xs(e){let t=Mg(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Io(e){switch(Xs(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Mg(e.path);return t?t.toUpperCase():"File"}}}function Eg(e){let t=e.markdown??"";return e.file?{filename:Dn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ei(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var kc="http://www.w3.org/2000/svg";function kg(e){let t=document.createElementNS(kc,"svg");t.setAttribute("class",Gn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(kc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(kc,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var Wo=(e,t,n)=>{let o=n;for(let r of t){let s=h("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Pg(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Wo(e,t,0)}var Pc="persona-artifact-status-label",Lg="persona-artifact-status-detail",Rg="data-artifact-status-label",Lc=new Map,Ig=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function qr(e){e&&Lc.delete(e)}function vb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Io(t):e.artifactType==="component"?"Component":"Document"}function Vr(e,t,n){let o=vb(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,i=Lc.get(a);e.status!=="complete"&&i===void 0&&(i=Ig(),Lc.set(a,i));let d=i===void 0?0:Math.max(0,Ig()-i),p=e.artifactType==="component",c=!p&&typeof e.markdown=="string"?e.markdown:"",u=p?0:c.length,v=p||c===""?0:c.split(`
|
|
29
|
+
`).length,f=e.artifactType==="markdown"?e.file:void 0,b={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:v,elapsedMs:d,content:()=>p?"":c,surface:n};try{let C=s(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function xb(e){e.className=Pc,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function cr(e,t,n){let o=e.querySelector(`:scope > .${Pc}`);o||(o=h("span",Pc),e.appendChild(o)),o.getAttribute(Rg)!==t.label&&(xb(o),Pg(o,t.label,n),o.setAttribute(Rg,t.label));let r=e.querySelector(`:scope > .${Lg}`),s=t.detail;s?(r||(r=h("span",Lg),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Cb={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},wb=15e4,ki={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Ab(e,t){let n=(e||"").trim().toLowerCase();if(n&&ki[n])return ki[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(ki[r])return ki[r]}}return null}function Pi(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let d=i.re.exec(e);if(d&&d.index===o&&d[0].length>0){s(o);let p=i.map?i.map(d[0]):i.type;n.push({type:p,value:d[0]}),o+=d[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var Sb=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Tb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Sb.has(e)?"keyword":"plain"}];function Wg(e){return Pi(e,Tb)}var Mb=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Eb(e){let t=Pi(e,Mb);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var kb=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Hg(e){let t=Pi(e,kb),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var Pb=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function Lb(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,d=e.slice(r,i);for(let c of Pi(d,Pb))t.push(c);r=i;let p=/^<\s*(script|style)\b/i.exec(d);if(p&&!/\/>\s*$/.test(d)){let c=p[1].toLowerCase(),v=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),f=v?r+v.index:o,b=e.slice(r,f),C=c==="script"?Wg(b):Hg(b);for(let E of C)t.push(E);r=f}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Rb(e,t){switch(t){case"html":return Lb(e);case"css":return Hg(e);case"js":return Wg(e);case"json":return Eb(e)}}function Ib(e){let t=Tu(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=Cb[r];if(a){let i=h("span",a);i.textContent=s,n.appendChild(i)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
|
|
30
30
|
`);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
31
|
-
`)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function yf(e,t,n){let o=e.length<=Qy?Zy(t,n):null,r=o?ib(e,o):[{type:"plain",value:e}];return lb(r)}function Lo(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(mi)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",f.id),f.destructive&&y.setAttribute("data-destructive",""),f.icon){let k=re(f.icon,16,"currentColor",1.5);k&&y.appendChild(k)}let C=document.createElement("span");C.textContent=f.label,y.appendChild(C),y.addEventListener("click",k=>{k.stopPropagation(),c(),n(f.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function p(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=y=>{!a.contains(y.target)&&!o.contains(y.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?p():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:p,hide:c,toggle:u,destroy:b}}function dt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=m("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=re(t,o??16,"currentColor",r??2);if(p&&d.appendChild(p),a&&d.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))d.setAttribute(c,u);return d}function Yn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let c=m("button",p);if(c.type="button",c.setAttribute("aria-label",n),t){let b=re(t,s??14,"currentColor",2);b&&c.appendChild(b)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),d)for(let[b,f]of Object.entries(d))c.setAttribute(b,f);return c}function Qn(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=dt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,d(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,d(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),s.appendChild(u)}function p(c){a=c,d()}return{element:s,setSelected:p}}function Ti(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,p=m("div","persona-combo-btn"+(i?" "+i:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,p.appendChild(c);let u=re(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",p.appendChild(u)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let b=Lo({items:o,onSelect:f=>{p.setAttribute("aria-expanded","false"),r(f)},anchor:p,position:s,portal:a});return a||p.appendChild(b.element),p.addEventListener("click",f=>{f.stopPropagation();let y=!b.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),b.toggle()}),p.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),p.click())}),{element:p,setLabel:f=>{c.textContent=f,p.setAttribute("aria-label",f)},open:()=>{p.setAttribute("aria-expanded","true"),b.show()},close:()=>{p.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),p.remove()}}}var Mi="persona-artifact-custom-action-btn";function jr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Mi+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+Mi+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=m("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Yn({icon:e.icon,label:e.label,className:Mi+(n?" persona-artifact-doc-copy-btn":"")}):o=dt({icon:e.icon,label:e.label,className:Mi+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function zs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function bf(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Wn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",d=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,p=n?ko(n):i==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 b=document.createElement("div");b.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let y=document.createElement("div");if(y.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",y.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,k={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},L=$r(k,C,"card");rr(y,L,C)}else s&&_r(s),y.textContent=p;if(b.append(f,y),c.append(u,b),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let L={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let H of C)try{if(H.visible===void 0||H.visible(L)){let E=jr(H);E.setAttribute("data-artifact-custom-action",H.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let k=Yn({label:"Download",className:"persona-flex-shrink-0"});k.title=`Download ${r}`,k.setAttribute("data-download-artifact",s),c.append(k)}return c}var Ei=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>bf(e,t)});if(i)return i}return bf(e,t)};var Ro=new WeakMap;function Tc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Ro.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Af(e){return Ro.has(e)}function cb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,i=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:i,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function vf(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Wn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?ko(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function db(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var xf=180,pb=240,ub=.8,fb=300,gb=500,mb="cubic-bezier(0.2, 0, 0, 1)",Cf=240,hb=.35;function yb(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:xf,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let d=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!d||Math.abs(d-t)<1){i(),r();return}let p=Math.abs(t-d),c=Math.round(Math.min(gb,Math.max(fb,pb+p*ub))),u=Math.round(c*hb),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:Cf,delay:u,easing:"ease-out",fill:"backwards"}):null,y=e.animate([{height:`${t}px`},{height:`${d}px`}],{duration:c,easing:mb});e.style.height=`${d}px`;let C=!1,k=()=>{C||(C=!0,i(),r())};Promise.allSettled([y.finished,f?.finished].filter(Boolean)).then(k),window.setTimeout(k,Math.max(c,u+Cf)+120)},xf)}function bb(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var qs="--persona-artifact-inline-body-height";function vb(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",d=i==="clip"?!1:t?.followOutput!==!1,p,c,u=t?.fadeMask;u===!0?(p=!0,c=!0):u===!1?(p=!1,c=!1):u&&typeof u=="object"?(p=u.top===!0,c=u.bottom===!0):i==="clip"?(p=!1,c=!0):(p=!0,c=!0);let b=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:i,fadeTop:p,fadeBottom:c,transition:b,completeDisplay:f}}function wf(e,t){let n=cb(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=bb(o),d=o?.inlineActions??[],p=vb(o),c=p.completeDisplay==="card",u=null,b=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let y=ee=>Ei(db(ee),t),C=ee=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(qs),f.replaceChildren(y(ee)),Ro.set(f,de=>{f.replaceChildren(y(de))})};if(c&&n.status==="complete")return C(n),f;let k=ki(n,{config:t.config,bodyLayout:p,resolveViewMode:()=>u??p.viewMode}),L=m("div","persona-artifact-inline-body");L.appendChild(k.el);let H=ee=>{let de=ee.status!=="complete",Z=de?p.streamingHeight:p.completeHeight,ue=typeof Z=="number";ue?f.style.setProperty(qs,`${Z}px`):f.style.removeProperty(qs);let xe=!!k.el.querySelector(".persona-code-pre"),ye=!!k.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",xe),L.classList.toggle("persona-artifact-inline-body--sized",ue&&ye),L.classList.toggle("persona-artifact-inline-body--cap",!de&&!ye&&typeof p.completeHeight=="number")},E=n.status,P=(ee,de)=>{E!=="complete"&&ee.status==="complete"?(typeof p.completeHeight=="number"?f.style.setProperty(qs,`${p.completeHeight}px`):f.style.removeProperty(qs),Tf(L,de?.suppressTransition?"none":p.transition,ee.id,()=>{k.update(ee),H(ee)})):k.update(ee),H(ee),E=ee.status};H(n);let _=p.overflow==="clip"&&a&&!!n.id;if(_&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${vf(n).title} in panel`)),!r)return f.appendChild(L),Ro.set(f,P),f;let q=m("div","persona-artifact-inline-chrome");q.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),z=m("span","persona-flex persona-items-center persona-flex-shrink-0"),V=re("file-text",16,"currentColor",2);V&&z.appendChild(V);let te=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=m("span","persona-artifact-inline-type");w.append(z,te,O);let j=m("div","persona-artifact-inline-chrome-actions"),Y=m("span","persona-flex persona-items-center persona-gap-1"),be=()=>u??p.viewMode,ve=i?Qn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:be(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ee=>{let de=ee==="source"?"source":"rendered";de!==be()&&(u=de,k.update(b),H(b))}}):null,Be=s?dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Be&&n.id&&Be.setAttribute("data-copy-artifact",n.id);let se=a?dt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-expand-artifact-inline",n.id),j.appendChild(Y),ve&&j.appendChild(ve.element),Be&&j.appendChild(Be),se&&j.appendChild(se),q.append(w,j),f.append(q,L);let he=ee=>{let{title:de,typeLabel:Z}=vf(ee);te.textContent=de,te.title=de,_&&L.setAttribute("aria-label",`Open ${de} in panel`);let ue=ee.status!=="complete";if(ue){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let xe=$r(ee,o,"inline-chrome");rr(O,xe,o)}else _r(ee.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=Z;if(Be&&Be.classList.toggle("persona-hidden",ue),ve){let xe=ee.artifactType==="markdown"?ee.file:void 0,ye=!1;if(!ue&&xe&&p.viewMode!=="source"){let Se=Us(xe);Se==="markdown"?ye=!0:(Se==="html"||Se==="svg")&&(ye=o?.filePreview?.enabled!==!1)}ve.element.classList.toggle("persona-hidden",!ye),ve.setSelected(be())}if(Y.replaceChildren(),!ue&&d.length>0){let xe=zs(ee);if(xe)for(let ye of d)try{if(ye.visible===void 0||ye.visible(xe)){let Se=jr(ye,{documentChrome:!0});Se.setAttribute("data-artifact-custom-action",ye.id),Se.classList.add("persona-flex-shrink-0"),Y.appendChild(Se)}}catch{}}};return he(n),Ro.set(f,(ee,de)=>{if(c&&E!=="complete"&&ee.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;E="complete";let ue=ee,xe=!1,ye=Se=>{ue=Se,xe=!0};Ro.set(f,ye),yb(f,Z,{swap:()=>{C(ue),xe=!1,Ro.set(f,ye)},onSettled:()=>{xe?C(ue):Ro.set(f,Se=>{f.replaceChildren(y(Se))})}});return}(ee.status!=="complete"||ee.id!==b.id)&&(u=null),b=ee,P(ee,de),he(ee)}),f}var Sf=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>wf(e,t)});if(i)return i}return wf(e,t)};var Mc=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Mn=new Mc;Mn.register("PersonaArtifactCard",Ei,{bubbleChrome:!1});Mn.register("PersonaArtifactInline",Sf,{bubbleChrome:!1});function Vs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?wi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Ec=!1;function xb(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Tf(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||Ec||s){o();return}Ec=!0;let a=xb(n);e.style.setProperty("view-transition-name",a);let i=()=>{Ec=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Cb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",wb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Ab(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Sb(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Tb=220;function Mb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Eb(e){return`
|
|
32
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function kb(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(df());let s=null;return n.label!==!1&&(s=m("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function Pb(e,t,n,o,r,s){let a=null,i=0,d=!1,p=new Set,c=()=>{p.forEach(E=>clearTimeout(E)),p.clear()},u=(E,P)=>{let _=setTimeout(()=>{p.delete(_),E()},P);p.add(_)},b=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||d)return;let E=kb(r,s,o);a=E.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(E.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(b,Tb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",H)},k=()=>{if(d||(d=!0,C(),c(),!a))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-i));E>0?u(y,E):y()};function L(E){if(n===null)return;let P=E.data;!P||P.persona!=="artifact-preview-ready"||P.token!==n||E.source===t.contentWindow&&k()}function H(){let E=P=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>P()):setTimeout(P,0)};E(()=>E(()=>k()))}return u(f,o.delayMs),u(k,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",H),()=>{d=!0,c(),C(),b()}}function ki(e,t){let{config:n}=t,o=t.registry??Mn,r=t.bodyLayout,s=n.markdown?Yo(n.markdown):null,a=kr(n.sanitize),i=e,d=!1,p=se=>{let he=zn()!==null;s&&!he&&!d&&(d=!0,Er(()=>Be(i)));let ee=s?s(se):Rn(se);return s&&he&&a?a(ee):ee},c=m("div","persona-artifact-preview-body"),u=null,b=null,f=null,y=()=>{f&&(f(),f=null),u=null,b=null},C=null,k=null,L=null,H=!1,E=()=>{C=null,k=null,L=null,H=!1},P=null,_=null,q=()=>{P=null,_=null},w=40,z=0,V=se=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>se()):setTimeout(se,0),te=se=>se.scrollHeight-se.clientHeight-se.scrollTop<=w,O=se=>{if(!r)return;let he=se.scrollHeight-se.clientHeight>1,ee=se.scrollHeight-se.clientHeight-se.scrollTop;se.classList.toggle("persona-artifact-fade-top",r.fadeTop&&he&&se.scrollTop>1),se.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&he&&ee>1)},j=se=>{z||(z=V(()=>{z=0,se.scrollTop=se.scrollHeight,O(se)}))},Y=(se,he,ee,de)=>{let Z=!!r,ue=ee.id+"|"+(Z?"w":"p");if(!C||L!==ue||C.parentElement!==c){y(),q(),c.replaceChildren();let Se=m("pre",Cb+" persona-code-pre"),lt=m("code","persona-code");if(Se.appendChild(lt),Z){let Ee=m("div","persona-artifact-source-window");if(Ee.appendChild(Se),c.appendChild(Ee),!(r?.overflow==="clip")&&typeof Ee.addEventListener=="function"){let Ne=()=>Ee.scrollHeight-Ee.clientHeight>1;Ee.addEventListener("scroll",()=>{te(Ee)&&(H=!1),O(Ee)},{passive:!0}),Ee.addEventListener("wheel",qe=>{Ne()&&qe.deltaY<0&&(H=!0)},{passive:!0}),Ee.addEventListener("touchmove",()=>{Ne()&&(H=!0)},{passive:!0})}C=Ee}else c.appendChild(Se),C=Se;k=lt,L=ue}let xe=Z?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",de),xe.classList.toggle("persona-artifact-source-window--clip",de&&r?.overflow==="clip"));let ye=xe?te(xe):!0;if(k.replaceChildren(yf(se,he?.language,he?.path)),xe){let Se=ee.status!=="complete";de&&Se&&r?.followOutput&&!H&&ye?j(xe):Se||(H=!1),O(xe)}},be=se=>{y(),E(),q(),c.replaceChildren();let he=m("div",wb);he.innerHTML=p(se),c.appendChild(he)},ve=se=>{let he=se.id,ee=n.features?.artifacts,de=$r(se,ee,"status-body");if(P&&_===he&&P.parentElement===c){let xe=P.querySelector(".persona-artifact-status-view-text");xe&&rr(xe,de,ee);return}y(),E(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),ue=m("div","persona-artifact-status-view-text");rr(ue,de,ee),Z.appendChild(ue),c.appendChild(Z),P=Z,_=he},Be=se=>{i=se;let he=t.resolveViewMode?.(se)??r?.viewMode??"rendered",ee=se.artifactType==="markdown"?se.file:void 0,de=se.status!=="complete";de||_r(se.id);let Z=de?r?.streamingHeight:r?.completeHeight,ue=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&de){ve(se);return}if(ee){let ye=wi(se.markdown??""),Se=Us(ee),lt=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&he==="rendered"&<&&(Se==="html"||Se==="svg")){let De=se.id+"\0"+ye;if(u&&b===De&&u.parentElement===c)return;E(),q(),y(),c.replaceChildren();let Ne=n.features?.artifacts?.filePreview,qe=Ne?.iframeSandbox??"allow-scripts";!Ne?.dangerouslyAllowSameOrigin&&qe.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),qe=qe.split(/\s+/).filter(xt=>xt&&xt!=="allow-same-origin").join(" "));let Me=Sb(Ne?.loading),ce=m("div","persona-artifact-frame"),Le=m("iframe","persona-artifact-iframe");Le.setAttribute("sandbox",qe),Le.setAttribute("data-artifact-id",se.id);let st=null;Me.enabled&&Me.injectReadySignal?(st=Mb(),Le.srcdoc=ye+Eb(st)):Le.srcdoc=ye,ce.appendChild(Le),c.appendChild(ce),Me.enabled&&(f=Pb(ce,Le,st,Me,se.id,n)),u=ce,b=De;return}if(y(),!de&&Se==="markdown"&&he==="rendered"){be(ye);return}Y(ye,{language:ee.language,path:ee.path},se,ue);return}if(se.artifactType==="markdown"){if(he==="source"){y(),Y(se.markdown??"",void 0,se,ue);return}be(se.markdown??"");return}y(),E(),q(),c.replaceChildren();let xe=se.component?o.get(se.component):void 0;if(xe){let Se={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let lt=xe(se.props??{},Se);if(lt){c.appendChild(lt);return}}catch{}}c.appendChild(Ab(se))};return Be(e),{el:c,update(se){Be(se)}}}var Mf=require("idiomorph"),Pi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Mf.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var Ef=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var kc={index:-1,draft:""};function kf(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Pf(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Lf(){return new Map}function Rf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function If(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Wf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Hf(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Li(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Hn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Io(e,t){return Hn(e)-e.scrollTop<=t}function Ri(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!p||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ii(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Bf(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Df(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 Of(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ks={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lb=["pre","code","a","script","style"],Wi=e=>({type:e?.type??Ks.type,placeholder:e?.placeholder??Ks.placeholder,speed:e?.speed??Ks.speed,duration:e?.duration??Ks.duration,buffer:e?.buffer??Ks.buffer}),Ff=[{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"}],Gs=new Map;for(let e of Ff)Gs.set(e.name,e);var _f=e=>{Gs.set(e.name,e)},$f=e=>{Ff.some(t=>t.name===e)||Gs.delete(e)},jf=()=>Array.from(Gs.keys()),Ur=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Gs.get(e)??null,Hi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
33
|
-
`);return s<0?"":e.slice(0,s)}return e},Rb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Ib=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Pc=/\s/,Wb=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Hb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(Pc.test(s[i])){let d=i;for(;d<s.length&&Pc.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Pc.test(s[p]);)d.appendChild(Rb(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),i=p}r.replaceChild(a,e)},Bb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(Ib(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},Js=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??Lb).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Wb(d,s)||i.push(d),d=a.nextNode();let p={value:o?.startIndex??0},c=t==="char"?Hb:Bb;for(let u of i)c(u,n,p);return r.innerHTML},Bi=(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},Xs=(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},Nf=new WeakMap,Db=(e,t)=>{if(!e.styles)return;let n=Nf.get(t);if(n||(n=new Set,Nf.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Lc=new WeakMap,Ob=(e,t)=>{if(!e.onAttach)return;let n=Lc.get(t);if(n||(n=new Map,Lc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Uf=e=>{let t=Lc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Di=(e,t)=>{Db(e,t),Ob(e,t)};function Rc(e,t=Kt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Ys=0,Wo=null;function Ic(e=document){if(Ys++,Ys===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Wo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Ys=Math.max(0,Ys-1),Ys===0&&Wo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Wo.originalOverflow,n.style.position=Wo.originalPosition,n.style.top=Wo.originalTop,n.style.width=Wo.originalWidth,o.scrollTo(0,Wo.scrollY),Wo=null}}}var Qs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Pt=e=>(e?.launcher?.mountMode??"floating")==="docked",Ho=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",tn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Qs.side,width:t?.width??Qs.width,animate:t?.animate??Qs.animate,reveal:t?.reveal??Qs.reveal,maxHeight:t?.maxHeight??Qs.maxHeight}};var En={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Nb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Oi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Nb,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",d=m("div",o),p=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Fe("button",{className:qn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":p},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Xt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=re(u,s,"currentColor",1);return C?(C.style.display="block",y.appendChild(C)):y.textContent=b,d.appendChild(y),$t({anchor:y,trigger:d,text:()=>y.getAttribute("aria-label")??p,enabled:c}),{button:y,wrapper:d}},Fb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ni=(e,t={})=>{let{wrapperClassName:n=Fb,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",d=a.iconName??"refresh-cw",p=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",b=a.borderColor??"",f=a.borderRadius??"",y=a.paddingX??"",C=a.paddingY??"",k=a.tooltipText??"Clear chat",L=a.showTooltip??!0,H=m("div",n),E=!!(u||b),P=Fe("button",{className:qn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!E&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:i,width:i,color:p||Xt.actionIconColor,backgroundColor:c||void 0,border:E?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),_=re(d,r,"currentColor",1);return _&&(_.style.display="block",P.appendChild(_)),H.appendChild(P),$t({anchor:P,trigger:H,text:()=>P.getAttribute("aria-label")??k,enabled:L}),{button:P,wrapper:H}};var Xt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Zn=e=>{let{config:t,showClose:n=!0}=e,o=Fe("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,d=r.headerIconName,p=Fe("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let _=parseFloat(s)||24,q=re(d,_*.6,"currentColor",1);q?p.replaceChildren(q):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=m("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,p.replaceChildren(_)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Fe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor}}),b=Fe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor}});c.append(u,b),i?o.append(c):o.append(p,c);let f=r.clearChat??{},y=f.enabled??!0,C=f.placement??"inline",k=null,L=null;if(y){let q=Ni(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=q.button,L=q.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:P}=Oi(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&o.appendChild(P),{header:o,iconHolder:p,headerTitle:u,headerSubtitle:b,closeButton:E,closeButtonWrapper:P,clearChatButton:k,clearChatButtonWrapper:L}},sr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Wc=e=>{let t=Zn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function _b(e,t,n){if(t?.length)for(let o of t){let r=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=re(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=Lo({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Hc=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,c;if(d)p=Ti({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,p.style.color=Xt.titleColor,c=p.querySelector(".persona-combo-btn-label")??p;else{if(p=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Xt.titleColor,c.textContent=a.title??"Chat Assistant",p.appendChild(c),_b(p,r?.trailingActions,r?.onAction??s),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let E=r.onTitleClick;p.addEventListener("click",P=>{P.target.closest("button")||E()}),p.addEventListener("keydown",P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),E())})}let H=r?.titleRowHover;H&&(p.style.borderRadius=H.borderRadius??"10px",p.style.padding=H.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=H.background??"",p.style.borderColor=H.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}i.appendChild(p);let u=a.closeButtonSize??"32px",b=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Xt.actionIconColor;let y=a.closeButtonIconName??"x",C=re(y,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f),i.appendChild(b);let k=m("div");k.style.display="none";let L=m("span");return L.style.display="none",{header:i,iconHolder:k,headerTitle:c,headerSubtitle:L,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},Fi={default:Wc,minimal:Hc},Bc=e=>Fi[e]??Fi.default,zr=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let d=m("span"),p=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:d,headerSubtitle:p,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Bc(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var _i=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},$i=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",b=t.backgroundColor,f=t.textColor,y=m("div","persona-send-button-wrapper"),C=Fe("button",{className:qn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&b||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),k=null,L=null;if(n){let P=parseFloat(u)||24,_=f?.trim()||"currentColor";r?(k=re(r,P,_,2),k?C.appendChild(k):C.textContent=o):C.textContent=o,L=re(s,P,_,2)}else C.textContent=d;C.setAttribute("aria-label",a),y.appendChild(C),$t({anchor:C,trigger:y,text:()=>C.getAttribute("aria-label")??"",enabled:c});let H="send";return{button:C,wrapper:y,setMode:P=>{if(P===H)return;H=P;let _=P==="stop"?i:a;if(C.setAttribute("aria-label",_),n){if(k&&L){let q=P==="stop"?L:k;C.replaceChildren(q)}}else C.textContent=P==="stop"?p:d}}},ji=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",d=t.iconSize??a,p=parseFloat(d)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,b=m("div","persona-send-button-wrapper"),f=Fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=re(i,p,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let k=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return $t({anchor:f,trigger:b,text:()=>f.getAttribute("aria-label")??k,enabled:L}),{button:f,wrapper:b}},Ui=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Xn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),p=m("div","persona-send-button-wrapper"),c=Fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=re(s,d,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),p.appendChild(c);let b=t.buttonTooltipText??"Attach file";return $t({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:p,input:r,previewsContainer:o}},zi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},qi=()=>Fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var qr=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=qi(),r=Fe("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=_i(t);a();let i=$i(t),d=ji(t),p=Ui(t),c=zi(t);p&&(p.previewsContainer.style.gap="8px",r.append(p.previewsContainer,p.input)),r.append(s);let u=Fe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return p&&b.append(p.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(b,f),r.append(u),r.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:c,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:f,setSendButtonMode:i.setMode}};var zf=()=>{let e=Fe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=re("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=re("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},qf=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=qi(),r=zi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=_i(t);s.style.maxHeight="100px",a();let i=$i(t),d=ji(t),p=Ui(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let c=Fe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");p&&u.append(p.wrapper);let b=m("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&b.append(d.wrapper),b.append(i.wrapper),c.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&s.focus()}),p&&c.append(p.input),c.append(u,s,b),p&&n.append(p.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:b,setSendButtonMode:i.setMode}};var Vf=e=>{let t=e?.launcher?.enabled??!0,n=Pt(e);if(Ho(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Kt);let b=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Kt),{wrapper:u,panel:b,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=e?.launcher?.width??"100%";return c.style.width=b,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&En[r.position]?En[r.position]:En["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Kt);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??ln;return i.style.width=p,i.style.maxWidth=p,a.appendChild(i),{wrapper:a,panel:i}},$b=(e,t)=>{let n=m("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Oi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let P=Ni(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=P.button,i=P.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Fe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Fe("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let c=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=m("div","persona-flex persona-flex-col persona-gap-3"),y=e?.layout?.contentMaxWidth;y&&(f.style.maxWidth=y,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(b.style.display="none",p.classList.remove("persona-gap-6"),p.classList.add("persona-gap-3")),p.append(b,f);let k=Fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=qf({config:e}),{root:H,textNode:E}=zf();return n.append(d,r,p,k),i&&n.appendChild(i),{container:n,body:p,messagesWrapper:f,composerOverlay:k,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:d,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:H,peekTextNode:E}},Kf=(e,t=!0)=>{if(Ho(e))return $b(e,t);let n=Fe("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?zr(e,o,{showClose:t}):Zn({config:e,showClose:t}),a=Fe("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),d=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),p=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Pt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,d),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(p.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(p,c);let f=qr({config:e}),y=e?.layout?.showFooter!==!1;r?sr(n,s,e):(s.header.style.display="none",sr(n,s,e)),n.append(a);let C=Fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return y||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Dc=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
|
|
31
|
+
`)),n=h("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Bg(e,t,n){let o=e.length<=wb?Ab(t,n):null,r=o?Rb(e,o):[{type:"plain",value:e}];return Ib(r)}function Ho(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(xi)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",f.id),f.destructive&&b.setAttribute("data-destructive",""),f.icon){let E=re(f.icon,16,"currentColor",1.5);E&&b.appendChild(E)}let C=document.createElement("span");C.textContent=f.label,b.appendChild(C),b.addEventListener("click",E=>{E.stopPropagation(),c(),n(f.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function p(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=b=>{!a.contains(b.target)&&!o.contains(b.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?p():c()}function v(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:p,hide:c,toggle:u,destroy:v}}function it(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=re(t,o??16,"currentColor",r??2);if(p&&d.appendChild(p),a&&d.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))d.setAttribute(c,u);return d}function eo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let c=h("button",p);if(c.type="button",c.setAttribute("aria-label",n),t){let v=re(t,s??14,"currentColor",2);v&&c.appendChild(v)}let u=h("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),d)for(let[v,f]of Object.entries(d))c.setAttribute(v,f);return c}function to(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=h("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=it({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,d(),o(c.id)}}):(u=h("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,d(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),s.appendChild(u)}function p(c){a=c,d()}return{element:s,setSelected:p}}function Li(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,p=h("div","persona-combo-btn"+(i?" "+i:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let c=h("span","persona-combo-btn-label");c.textContent=t,p.appendChild(c);let u=re(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",p.appendChild(u)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let v=Ho({items:o,onSelect:f=>{p.setAttribute("aria-expanded","false"),r(f)},anchor:p,position:s,portal:a});return a||p.appendChild(v.element),p.addEventListener("click",f=>{f.stopPropagation();let b=!v.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),v.toggle()}),p.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),p.click())}),{element:p,setLabel:f=>{c.textContent=f,p.setAttribute("aria-label",f)},open:()=>{p.setAttribute("aria-expanded","true"),v.show()},close:()=>{p.setAttribute("aria-expanded","false"),v.hide()},toggle:()=>{let f=!v.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",f?"false":"true"),v.toggle()},destroy:()=>{v.destroy(),p.remove()}}}var Ri="persona-artifact-custom-action-btn";function Kr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Ri+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Ri+(n?" persona-artifact-doc-icon-btn":"");o=h("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=h("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=eo({icon:e.icon,label:e.label,className:Ri+(n?" persona-artifact-doc-copy-btn":"")}):o=it({icon:e.icon,label:e.label,className:Ri+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ys(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Dg(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Dn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",d=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,p=n?Io(n):i==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 v=document.createElement("div");v.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,E={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},L=Vr(E,C,"card");cr(b,L,C)}else s&&qr(s),b.textContent=p;if(v.append(f,b),c.append(u,v),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let L={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let W of C)try{if(W.visible===void 0||W.visible(L)){let A=Kr(W);A.setAttribute("data-artifact-custom-action",W.id),A.className=`${A.className} persona-flex-shrink-0`,c.append(A)}}catch{}}let E=eo({label:"Download",className:"persona-flex-shrink-0"});E.title=`Download ${r}`,E.setAttribute("data-download-artifact",s),c.append(E)}return c}var Ii=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Dg(e,t)});if(i)return i}return Dg(e,t)};var Bo=new WeakMap;function Rc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Bo.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function $g(e){return Bo.has(e)}function Wb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,i=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:i,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Og(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Dn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Io(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Hb(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Ng=180,Bb=240,Db=.8,Ob=300,Nb=500,Fb="cubic-bezier(0.2, 0, 0, 1)",Fg=240,_b=.35;function $b(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:Ng,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let d=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!d||Math.abs(d-t)<1){i(),r();return}let p=Math.abs(t-d),c=Math.round(Math.min(Nb,Math.max(Ob,Bb+p*Db))),u=Math.round(c*_b),v=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=v?v.animate([{opacity:0},{opacity:1}],{duration:Fg,delay:u,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${d}px`}],{duration:c,easing:Fb});e.style.height=`${d}px`;let C=!1,E=()=>{C||(C=!0,i(),r())};Promise.allSettled([b.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(c,u+Fg)+120)},Ng)}function jb(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Qs="--persona-artifact-inline-body-height";function Ub(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",d=i==="clip"?!1:t?.followOutput!==!1,p,c,u=t?.fadeMask;u===!0?(p=!0,c=!0):u===!1?(p=!1,c=!1):u&&typeof u=="object"?(p=u.top===!0,c=u.bottom===!0):i==="clip"?(p=!1,c=!0):(p=!0,c=!0);let v=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:i,fadeTop:p,fadeBottom:c,transition:v,completeDisplay:f}}function _g(e,t){let n=Wb(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=jb(o),d=o?.inlineActions??[],p=Ub(o),c=p.completeDisplay==="card",u=null,v=n,f=h("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let b=te=>Ii(Hb(te),t),C=te=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Qs),f.replaceChildren(b(te)),Bo.set(f,de=>{f.replaceChildren(b(de))})};if(c&&n.status==="complete")return C(n),f;let E=Wi(n,{config:t.config,bodyLayout:p,resolveViewMode:()=>u??p.viewMode}),L=h("div","persona-artifact-inline-body");L.appendChild(E.el);let W=te=>{let de=te.status!=="complete",Q=de?p.streamingHeight:p.completeHeight,me=typeof Q=="number";me?f.style.setProperty(Qs,`${Q}px`):f.style.removeProperty(Qs);let xe=!!E.el.querySelector(".persona-code-pre"),ye=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",xe),L.classList.toggle("persona-artifact-inline-body--sized",me&&ye),L.classList.toggle("persona-artifact-inline-body--cap",!de&&!ye&&typeof p.completeHeight=="number")},A=n.status,k=(te,de)=>{A!=="complete"&&te.status==="complete"?(typeof p.completeHeight=="number"?f.style.setProperty(Qs,`${p.completeHeight}px`):f.style.removeProperty(Qs),Ug(L,de?.suppressTransition?"none":p.transition,te.id,()=>{E.update(te),W(te)})):E.update(te),W(te),A=te.status};W(n);let F=p.overflow==="clip"&&a&&!!n.id;if(F&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${Og(n).title} in panel`)),!r)return f.appendChild(L),Bo.set(f,k),f;let q=h("div","persona-artifact-inline-chrome");q.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let S=h("div","persona-artifact-inline-chrome-lead"),V=h("span","persona-flex persona-items-center persona-flex-shrink-0"),G=re("file-text",16,"currentColor",2);G&&V.appendChild(G);let oe=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),N=h("span","persona-artifact-inline-type");S.append(V,oe,N);let U=h("div","persona-artifact-inline-chrome-actions"),Z=h("span","persona-flex persona-items-center persona-gap-1"),he=()=>u??p.viewMode,ve=i?to({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:he(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:te=>{let de=te==="source"?"source":"rendered";de!==he()&&(u=de,E.update(v),W(v))}}):null,ue=s?it({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ue&&n.id&&ue.setAttribute("data-copy-artifact",n.id);let ne=a?it({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-expand-artifact-inline",n.id),U.appendChild(Z),ve&&U.appendChild(ve.element),ue&&U.appendChild(ue),ne&&U.appendChild(ne),q.append(S,U),f.append(q,L);let fe=te=>{let{title:de,typeLabel:Q}=Og(te);oe.textContent=de,oe.title=de,F&&L.setAttribute("aria-label",`Open ${de} in panel`);let me=te.status!=="complete";if(me){N.classList.contains("persona-artifact-inline-status")||(N.className="persona-artifact-inline-status",N.removeAttribute("data-preserve-animation"),N.replaceChildren());let xe=Vr(te,o,"inline-chrome");cr(N,xe,o)}else qr(te.id),N.className="persona-artifact-inline-type",N.removeAttribute("data-preserve-animation"),N.replaceChildren(),N.textContent=Q;if(ue&&ue.classList.toggle("persona-hidden",me),ve){let xe=te.artifactType==="markdown"?te.file:void 0,ye=!1;if(!me&&xe&&p.viewMode!=="source"){let Ae=Xs(xe);Ae==="markdown"?ye=!0:(Ae==="html"||Ae==="svg")&&(ye=o?.filePreview?.enabled!==!1)}ve.element.classList.toggle("persona-hidden",!ye),ve.setSelected(he())}if(Z.replaceChildren(),!me&&d.length>0){let xe=Ys(te);if(xe)for(let ye of d)try{if(ye.visible===void 0||ye.visible(xe)){let Ae=Kr(ye,{documentChrome:!0});Ae.setAttribute("data-artifact-custom-action",ye.id),Ae.classList.add("persona-flex-shrink-0"),Z.appendChild(Ae)}}catch{}}};return fe(n),Bo.set(f,(te,de)=>{if(c&&A!=="complete"&&te.status==="complete"){let Q=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let me=te,xe=!1,ye=Ae=>{me=Ae,xe=!0};Bo.set(f,ye),$b(f,Q,{swap:()=>{C(me),xe=!1,Bo.set(f,ye)},onSettled:()=>{xe?C(me):Bo.set(f,Ae=>{f.replaceChildren(b(Ae))})}});return}(te.status!=="complete"||te.id!==v.id)&&(u=null),v=te,k(te,de),fe(te)}),f}var jg=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>_g(e,t)});if(i)return i}return _g(e,t)};var Ic=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},kn=new Ic;kn.register("PersonaArtifactCard",Ii,{bubbleChrome:!1});kn.register("PersonaArtifactInline",jg,{bubbleChrome:!1});function Zs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ei(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Wc=!1;function zb(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Ug(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||Wc||s){o();return}Wc=!0;let a=zb(n);e.style.setProperty("view-transition-name",a);let i=()=>{Wc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var qb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Vb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Kb(e){let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Gb(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Jb=220;function Xb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Yb(e){return`
|
|
32
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Qb(e,t,n){let o=h("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=h("div","persona-artifact-frame-loading-indicator");r.appendChild(kg());let s=null;return n.label!==!1&&(s=h("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function Zb(e,t,n,o,r,s){let a=null,i=0,d=!1,p=new Set,c=()=>{p.forEach(A=>clearTimeout(A)),p.clear()},u=(A,k)=>{let F=setTimeout(()=>{p.delete(F),A()},k);p.add(F)},v=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||d)return;let A=Qb(r,s,o);a=A.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(v,Jb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",W)},E=()=>{if(d||(d=!0,C(),c(),!a))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-i));A>0?u(b,A):b()};function L(A){if(n===null)return;let k=A.data;!k||k.persona!=="artifact-preview-ready"||k.token!==n||A.source===t.contentWindow&&E()}function W(){let A=k=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>k()):setTimeout(k,0)};A(()=>A(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",W),()=>{d=!0,c(),C(),v()}}function Wi(e,t){let{config:n}=t,o=t.registry??kn,r=t.bodyLayout,s=n.markdown?tr(n.markdown):null,a=Wr(n.sanitize),i=e,d=!1,p=ne=>{let fe=Kn()!==null;s&&!fe&&!d&&(d=!0,Ir(()=>ue(i)));let te=s?s(ne):Hn(ne);return s&&fe&&a?a(te):te},c=h("div","persona-artifact-preview-body"),u=null,v=null,f=null,b=()=>{f&&(f(),f=null),u=null,v=null},C=null,E=null,L=null,W=!1,A=()=>{C=null,E=null,L=null,W=!1},k=null,F=null,q=()=>{k=null,F=null},S=40,V=0,G=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),oe=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=S,N=ne=>{if(!r)return;let fe=ne.scrollHeight-ne.clientHeight>1,te=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&fe&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&fe&&te>1)},U=ne=>{V||(V=G(()=>{V=0,ne.scrollTop=ne.scrollHeight,N(ne)}))},Z=(ne,fe,te,de)=>{let Q=!!r,me=te.id+"|"+(Q?"w":"p");if(!C||L!==me||C.parentElement!==c){b(),q(),c.replaceChildren();let Ae=h("pre",qb+" persona-code-pre"),Ee=h("code","persona-code");if(Ae.appendChild(Ee),Q){let Se=h("div","persona-artifact-source-window");if(Se.appendChild(Ae),c.appendChild(Se),!(r?.overflow==="clip")&&typeof Se.addEventListener=="function"){let Fe=()=>Se.scrollHeight-Se.clientHeight>1;Se.addEventListener("scroll",()=>{oe(Se)&&(W=!1),N(Se)},{passive:!0}),Se.addEventListener("wheel",Ue=>{Fe()&&Ue.deltaY<0&&(W=!0)},{passive:!0}),Se.addEventListener("touchmove",()=>{Fe()&&(W=!0)},{passive:!0})}C=Se}else c.appendChild(Ae),C=Ae;E=Ee,L=me}let xe=Q?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",de),xe.classList.toggle("persona-artifact-source-window--clip",de&&r?.overflow==="clip"));let ye=xe?oe(xe):!0;if(E.replaceChildren(Bg(ne,fe?.language,fe?.path)),xe){let Ae=te.status!=="complete";de&&Ae&&r?.followOutput&&!W&&ye?U(xe):Ae||(W=!1),N(xe)}},he=ne=>{b(),A(),q(),c.replaceChildren();let fe=h("div",Vb);fe.innerHTML=p(ne),c.appendChild(fe)},ve=ne=>{let fe=ne.id,te=n.features?.artifacts,de=Vr(ne,te,"status-body");if(k&&F===fe&&k.parentElement===c){let xe=k.querySelector(".persona-artifact-status-view-text");xe&&cr(xe,de,te);return}b(),A(),c.replaceChildren();let Q=h("div","persona-artifact-status-view"),me=h("div","persona-artifact-status-view-text");cr(me,de,te),Q.appendChild(me),c.appendChild(Q),k=Q,F=fe},ue=ne=>{i=ne;let fe=t.resolveViewMode?.(ne)??r?.viewMode??"rendered",te=ne.artifactType==="markdown"?ne.file:void 0,de=ne.status!=="complete";de||qr(ne.id);let Q=de?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof Q=="number";if(r?.streamingView==="status"&&de){ve(ne);return}if(te){let ye=Ei(ne.markdown??""),Ae=Xs(te),Ee=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&fe==="rendered"&&Ee&&(Ae==="html"||Ae==="svg")){let Te=ne.id+"\0"+ye;if(u&&v===Te&&u.parentElement===c)return;A(),q(),b(),c.replaceChildren();let Fe=n.features?.artifacts?.filePreview,Ue=Fe?.iframeSandbox??"allow-scripts";!Fe?.dangerouslyAllowSameOrigin&&Ue.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ue=Ue.split(/\s+/).filter(bt=>bt&&bt!=="allow-same-origin").join(" "));let ke=Gb(Fe?.loading),ce=h("div","persona-artifact-frame"),We=h("iframe","persona-artifact-iframe");We.setAttribute("sandbox",Ue),We.setAttribute("data-artifact-id",ne.id);let ot=null;ke.enabled&&ke.injectReadySignal?(ot=Xb(),We.srcdoc=ye+Yb(ot)):We.srcdoc=ye,ce.appendChild(We),c.appendChild(ce),ke.enabled&&(f=Zb(ce,We,ot,ke,ne.id,n)),u=ce,v=Te;return}if(b(),!de&&Ae==="markdown"&&fe==="rendered"){he(ye);return}Z(ye,{language:te.language,path:te.path},ne,me);return}if(ne.artifactType==="markdown"){if(fe==="source"){b(),Z(ne.markdown??"",void 0,ne,me);return}he(ne.markdown??"");return}b(),A(),q(),c.replaceChildren();let xe=ne.component?o.get(ne.component):void 0;if(xe){let Ae={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ee=xe(ne.props??{},Ae);if(Ee){c.appendChild(Ee);return}}catch{}}c.appendChild(Kb(ne))};return ue(e),{el:c,update(ne){ue(ne)}}}var zg=require("idiomorph"),Hi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;zg.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var qg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Hc={index:-1,draft:""};function Vg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Kg(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Gg(){return new Map}function Jg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Xg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Yg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Qg(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Bi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function On(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Do(e,t){return On(e)-e.scrollTop<=t}function Di(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!p||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Oi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Zg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ef(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 tf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ea={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ev=["pre","code","a","script","style"],Ni=e=>({type:e?.type??ea.type,placeholder:e?.placeholder??ea.placeholder,speed:e?.speed??ea.speed,duration:e?.duration??ea.duration,buffer:e?.buffer??ea.buffer}),of=[{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"}],ta=new Map;for(let e of of)ta.set(e.name,e);var rf=e=>{ta.set(e.name,e)},sf=e=>{of.some(t=>t.name===e)||ta.delete(e)},af=()=>Array.from(ta.keys()),Gr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ta.get(e)??null,Fi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
33
|
+
`);return s<0?"":e.slice(0,s)}return e},tv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},nv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Bc=/\s/,ov=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},rv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(Bc.test(s[i])){let d=i;for(;d<s.length&&Bc.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Bc.test(s[p]);)d.appendChild(tv(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),i=p}r.replaceChild(a,e)},sv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(nv(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},na=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??ev).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)ov(d,s)||i.push(d),d=a.nextNode();let p={value:o?.startIndex??0},c=t==="char"?rv:sv;for(let u of i)c(u,n,p);return r.innerHTML},_i=(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},oa=(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},nf=new WeakMap,av=(e,t)=>{if(!e.styles)return;let n=nf.get(t);if(n||(n=new Set,nf.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Dc=new WeakMap,iv=(e,t)=>{if(!e.onAttach)return;let n=Dc.get(t);if(n||(n=new Map,Dc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},lf=e=>{let t=Dc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},$i=(e,t)=>{av(e,t),iv(e,t)};function Oc(e,t=Kt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var ra=0,Oo=null;function Nc(e=document){if(ra++,ra===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Oo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,ra=Math.max(0,ra-1),ra===0&&Oo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Oo.originalOverflow,n.style.position=Oo.originalPosition,n.style.top=Oo.originalTop,n.style.width=Oo.originalWidth,o.scrollTo(0,Oo.scrollY),Oo=null}}}var sa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Pt=e=>(e?.launcher?.mountMode??"floating")==="docked",No=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",on=e=>{let t=e?.launcher?.dock;return{side:t?.side??sa.side,width:t?.width??sa.width,animate:t?.animate??sa.animate,reveal:t?.reveal??sa.reveal,maxHeight:t?.maxHeight??sa.maxHeight}};var Fc=e=>e==="followUp"?"follow-up":e,lv=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},cv=e=>{switch(e){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'}},cf=new WeakSet,dv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,pv=e=>{dv()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},ji=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let u=getComputedStyle(e).direction==="rtl",v=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),f=4,b=v<=f,C=v>=c-f,E=u?!C:!b,L=u?!b:!C;e.toggleAttribute("data-scroll-left",E),e.toggleAttribute("data-scroll-right",L)},i=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",i,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(i):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",i),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,u,v,f,b,C)=>{e.replaceChildren(),t.length=0,n.length=0;let E=C?.source??"config",L=C?.surface??(E==="config"?"starter":"followUp"),W=L==="followUp",A=C?.variant??"chip",k=C?.behavior??"send",F=C?.overflow??"wrap",q=C?.config??{},S=C?.plugins??[],V=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,G=W?"followUps":"starters";!cf.has(q)&&q.debug===!0&&A!=="chip"&&q.suggestions?.[G]?.overflow!==void 0&&(cf.add(q),console.info(`[persona] suggestions.${G}.overflow applies to the "chip" variant only; the "${A}" variant manages its own stacking.`));let oe=ue=>ue.map(lv).filter(ne=>ne!==null).map(ne=>({...ne,behavior:ne.behavior??k})),N=oe(c??[]);S.forEach(ue=>{ue.transformSuggestions&&(N=oe(ue.transformSuggestions({suggestions:N.map(ne=>({...ne})),surface:L,source:E,config:q})))});let U=V===void 0?N:N.slice(0,V);if(!U.length){e.hidden=!0,o=null,s();return}if(!W&&(f??u.getMessages()).some(ne=>ne.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Fc(L),e.dataset.variant=A,e.dataset.overflow=F;let Z=document.createDocumentFragment(),he=u.isStreaming();U.forEach((ue,ne)=>{var xe,ye,Ae;let fe=ue.behavior,te=()=>{if(u.isStreaming())return;let Ee={suggestion:{...ue},surface:L,source:E,behavior:fe},Se=e.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:Ee,bubbles:!0,composed:!0,cancelable:!0}));if(W&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:ue.prompt},bubbles:!0,composed:!0})),!!Se){for(let Te of S)if(Te.onSuggestionSelect?.({suggestion:{...ue},surface:L,source:E,variant:A,config:q})===!1)return;if(fe==="fill"){v.value=ue.prompt,v.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),v.focus();return}v.value="",u.sendMessage(ue.prompt)}},de=()=>{let Ee=h("button",`persona-suggestion persona-suggestion--${A}`);if(Ee.type="button",Ee.disabled=he,Ee.dataset.suggestionId=ue.id,Ee.dataset.emphasis=ue.emphasis,Ee.dataset.behavior=fe,A==="chip"&&(b?.fontFamily&&(Ee.style.fontFamily=cv(b.fontFamily)),b?.fontWeight&&(Ee.style.fontWeight=b.fontWeight),b?.paddingX&&(Ee.style.paddingLeft=b.paddingX,Ee.style.paddingRight=b.paddingX),b?.paddingY&&(Ee.style.paddingTop=b.paddingY,Ee.style.paddingBottom=b.paddingY)),ue.icon){let Te=re(ue.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);Te&&(Te.classList.add("persona-suggestion__icon"),ue.iconColor&&(Te.style.color=ue.iconColor),Ee.appendChild(Te))}let Se=h("span","persona-suggestion__copy");if(Se.appendChild(Ie("span",{className:"persona-suggestion__label",text:ue.label})),ue.description&&Se.appendChild(Ie("span",{className:"persona-suggestion__description",text:ue.description})),Ee.appendChild(Se),A!=="chip"){let Te=re("arrow-right",16,"currentColor",1.8);Te&&(Te.classList.add("persona-suggestion__arrow"),Ee.appendChild(Te))}return Ee.addEventListener("click",te),Ee},Q=null;for(let Ee of S)if(Ee.renderSuggestion&&(Q=Ee.renderSuggestion({suggestion:{...ue},index:ne,surface:L,source:E,variant:A,streaming:he,config:q,defaultRenderer:de,select:te}),Q))break;Q??(Q=de()),(xe=Q.dataset).suggestionId||(xe.suggestionId=ue.id),(ye=Q.dataset).behavior||(ye.behavior=fe),(Ae=Q.dataset).emphasis||(Ae.emphasis=ue.emphasis),Q instanceof HTMLButtonElement||Q.setAttribute("aria-disabled",he?"true":"false"),Z.appendChild(Q),n.push(Q),[...Q instanceof HTMLButtonElement?[Q]:[],...Array.from(Q.querySelectorAll("button"))].forEach(Ee=>{t.includes(Ee)||(Ee.disabled=he,t.push(Ee))})}),e.appendChild(Z),a(),i();let ve=JSON.stringify({normalized:U,surface:L,variant:A,source:E});ve!==o&&(o=ve,pv(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:U.map(ue=>({...ue})),surface:L,source:E,variant:A},bubbles:!0,composed:!0})),W&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:U.map(ue=>ue.prompt)},bubbles:!0,composed:!0})))}}};var Pn={"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 uv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ui=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=uv,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",d=h("div",o),p=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",v=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Ie("button",{className:Gn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":p},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Qt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=re(u,s,"currentColor",1);return C?(C.style.display="block",b.appendChild(C)):b.textContent=v,d.appendChild(b),$t({anchor:b,trigger:d,text:()=>b.getAttribute("aria-label")??p,enabled:c}),{button:b,wrapper:d}},gv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",zi=(e,t={})=>{let{wrapperClassName:n=gv,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",d=a.iconName??"refresh-cw",p=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",v=a.borderColor??"",f=a.borderRadius??"",b=a.paddingX??"",C=a.paddingY??"",E=a.tooltipText??"Clear chat",L=a.showTooltip??!0,W=h("div",n),A=!!(u||v),k=Ie("button",{className:Gn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:p||Qt.actionIconColor,backgroundColor:c||void 0,border:A?`${u||"0px"} solid ${v||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),F=re(d,r,"currentColor",1);return F&&(F.style.display="block",k.appendChild(F)),W.appendChild(k),$t({anchor:k,trigger:W,text:()=>k.getAttribute("aria-label")??E,enabled:L}),{button:k,wrapper:W}};var Qt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},no=e=>{let{config:t,showClose:n=!0}=e,o=Ie("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,d=r.headerIconName,p=Ie("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let F=parseFloat(s)||24,q=re(d,F*.6,"currentColor",1);q?p.replaceChildren(q):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let F=h("img");F.src=t.launcher.iconUrl,F.alt="",F.className="persona-rounded-xl persona-object-cover",F.style.height=s,F.style.width=s,p.replaceChildren(F)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ie("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Qt.titleColor}}),v=Ie("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Qt.subtitleColor}});c.append(u,v),i?o.append(c):o.append(p,c);let f=r.clearChat??{},b=f.enabled??!0,C=f.placement??"inline",E=null,L=null;if(b){let q=zi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=q.button,L=q.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let W=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:A,wrapper:k}=Ui(t,{showClose:n,wrapperClassName:W});return a!=="top-right"&&o.appendChild(k),{header:o,iconHolder:p,headerTitle:u,headerSubtitle:v,closeButton:A,closeButtonWrapper:k,clearChatButton:E,clearChatButtonWrapper:L}},dr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var _c=e=>{let t=no({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function fv(e,t,n){if(t?.length)for(let o of t){let r=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=re(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=h("div","persona-relative");s.appendChild(r);let a=Ho({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var $c=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=h("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=r?.titleMenu,p,c;if(d)p=Li({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,p.style.color=Qt.titleColor,c=p.querySelector(".persona-combo-btn-label")??p;else{if(p=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=h("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Qt.titleColor,c.textContent=a.title??"Chat Assistant",p.appendChild(c),fv(p,r?.trailingActions,r?.onAction??s),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let A=r.onTitleClick;p.addEventListener("click",k=>{k.target.closest("button")||A()}),p.addEventListener("keydown",k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),A())})}let W=r?.titleRowHover;W&&(p.style.borderRadius=W.borderRadius??"10px",p.style.padding=W.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=W.background??"",p.style.borderColor=W.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}i.appendChild(p);let u=a.closeButtonSize??"32px",v=h("div",""),f=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Qt.actionIconColor;let b=a.closeButtonIconName??"x",C=re(b,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),v.appendChild(f),i.appendChild(v);let E=h("div");E.style.display="none";let L=h("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:c,headerSubtitle:L,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}},qi={default:_c,minimal:$c},jc=e=>qi[e]??qi.default,Jr=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=h("div");i.style.display="none";let d=h("span"),p=h("span"),c=h("button");c.style.display="none";let u=h("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:d,headerSubtitle:p,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=jc(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Vi=e=>{let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let d=t.ownerDocument?.defaultView;if(!d?.getComputedStyle)return o;let p=d.getComputedStyle(t).lineHeight;if(!p||!p.trim().endsWith("px"))return o;let c=parseFloat(p);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let d=t.style.maxHeight;if(d!==s){let c=parseFloat(d);if(Number.isFinite(c)&&c>0)return c}let p=n*r();return s=`${p}px`,t.style.maxHeight=s,p},i=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,a());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:i}},Ki=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",v=t.backgroundColor,f=t.textColor,b=h("div","persona-send-button-wrapper"),C=Ie("button",{className:Gn("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&&!v&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&v||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),E=null,L=null;if(n){let k=parseFloat(t.iconSize??"")||Math.round((parseFloat(u)||24)*.5),F=t.iconStrokeWidth??2,q=f?.trim()||"currentColor";r?(E=re(r,k,q,F),E?C.appendChild(E):C.textContent=o):C.textContent=o,L=re(s,k,q,F)}else C.textContent=d;C.setAttribute("aria-label",a),b.appendChild(C),$t({anchor:C,trigger:b,text:()=>C.getAttribute("aria-label")??"",enabled:c});let W="send";return{button:C,wrapper:b,setMode:k=>{if(k===W)return;W=k;let F=k==="stop"?i:a;if(C.setAttribute("aria-label",F),n){if(E&&L){let q=k==="stop"?L:E;C.replaceChildren(q)}}else C.textContent=k==="stop"?p:d}}},Gi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",d=t.iconSize??a,p=parseFloat(d)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,v=h("div","persona-send-button-wrapper"),f=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=re(i,p,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",v.appendChild(f);let E=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return $t({anchor:f,trigger:v,text:()=>f.getAttribute("aria-label")??E,enabled:L}),{button:f,wrapper:v}},Ji=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=h("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Zn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),p=h("div","persona-send-button-wrapper"),c=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=re(s,d,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),p.appendChild(c);let v=t.buttonTooltipText??"Attach file";return $t({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??v}),{button:c,wrapper:p,input:r,previewsContainer:o}},Xi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=h("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Yi=()=>Ie("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Xr=e=>{let{config:t}=e,n=Ie("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Yi(),r=Ie("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Vi(t);a();let i=Ki(t),d=Gi(t),p=Ji(t),c=Xi(t);p&&(p.previewsContainer.style.gap="8px",r.append(p.previewsContainer,p.input)),r.append(s);let u=Ie("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),v=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return p&&v.append(p.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(v,f),r.append(u),r.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:c,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:u,leftActions:v,rightActions:f,setSendButtonMode:i.setMode}};var df=()=>{let e=Ie("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=h("span","persona-pill-peek__icon"),n=re("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=re("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},pf=e=>{let{config:t}=e,n=Ie("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Yi(),r=Xi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Vi(t);s.style.maxHeight="100px",a();let i=Ki(t),d=Gi(t),p=Ji(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ie("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");p&&u.append(p.wrapper);let v=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&v.append(d.wrapper),v.append(i.wrapper),c.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&s.focus()}),p&&c.append(p.input),c.append(u,s,v),p&&n.append(p.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:v,setSendButtonMode:i.setMode}};var uf=e=>{let t=e?.launcher?.enabled??!0,n=Pt(e);if(No(e)){let c=e?.launcher?.composerBar??{},u=h("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Kt);let v=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");v.style.width="100%",u.appendChild(v);let f=h("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Kt),{wrapper:u,panel:v,pillRoot:f}}if(n){let c=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),v=e?.launcher?.width??"100%";return c.style.width=v,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Pn[r.position]?Pn[r.position]:Pn["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Kt);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??dn;return i.style.width=p,i.style.maxWidth=p,a.appendChild(i),{wrapper:a,panel:i}},Qi=e=>{let t=Ie("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Fc(e)}});return t.hidden=!0,t},mv=(e,t)=>{let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Ui(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let q=zi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=q.button,i=q.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Ie("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Ie("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"}});p.style.setProperty("scrollbar-gutter","stable");let c=Ie("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ie("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),v=Qi("starter"),f=Ie("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u,v),b=h("div","persona-flex persona-flex-col persona-gap-3"),C=Qi("followUp"),E=e?.layout?.contentMaxWidth;E&&(b.style.maxWidth=E,b.style.marginLeft="auto",b.style.marginRight="auto",b.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(f.style.display="none",p.classList.remove("persona-gap-6"),p.classList.add("persona-gap-3")),p.append(f,b,C);let W=Ie("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"}}),A=pf({config:e}),{root:k,textNode:F}=df();return n.append(d,r,p,W),i&&n.appendChild(i),{container:n,body:p,messagesWrapper:b,starterSuggestions:v,transcriptSuggestions:C,composerOverlay:W,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:k,peekTextNode:F}},gf=(e,t=!0)=>{if(No(e))return mv(e,t);let n=Ie("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Jr(e,o,{showClose:t}):no({config:e,showClose:t}),a=Ie("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=Ie("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),d=Ie("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),p=Qi("starter"),c=Ie("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Pt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,d,p),u=h("div","persona-flex persona-flex-col persona-gap-3"),v=Qi("followUp"),f=e?.layout?.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u,v);let C=Xr({config:e}),E=e?.layout?.showFooter!==!1;r?dr(n,s,e):(s.header.style.display="none",dr(n,s,e)),n.append(a);let L=Ie("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 E||(C.footer.style.display="none"),n.append(C.footer),n.append(L),{container:n,body:a,messagesWrapper:u,starterSuggestions:p,transcriptSuggestions:v,composerOverlay:L,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};var Uc=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
|
|
34
34
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
35
35
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
36
36
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -38,14 +38,14 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
38
38
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
39
39
|
</span>
|
|
40
40
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
41
|
-
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Pt(s),d=n.querySelector("[data-role='launcher-title']");if(d){let E=a.title??"Chat Assistant";d.textContent=E,d.setAttribute("title",E)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let E=a.subtitle??"Here to help you get answers fast";p.textContent=E,p.setAttribute("title",E)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let E=a.agentIconSize??"40px";if(u.style.height=E,u.style.width=E,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let P=parseFloat(E)||24,_=re(a.agentIconName,P*.6,"var(--persona-text-inverse, #ffffff)",2);_?(u.appendChild(_),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let E=a.agentIconSize??"40px";b.style.height=E,b.style.width=E,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let E=a.callToActionIconSize??"32px";f.style.height=E,f.style.width=E,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let P=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,P=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let _=parseFloat(E)||24,q=Math.max(_-P,8),w=re(a.callToActionIconName,q,"currentColor",2);w?f.appendChild(w):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&En[a.position]?En[a.position]:En["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?k:`${C} ${y}`,i||(n.style.zIndex=String(a.zIndex??Kt));let L="1px solid var(--persona-border, #e5e7eb)",H="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:H,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Gf=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Vf(e),s=Kf(e,t),a={wrapper:n,panel:o,pillRoot:r},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:p,replaceHeader:b=>(d.element.replaceWith(b.header),d.element=b.header,d.iconHolder=b.iconHolder,d.headerTitle=b.headerTitle,d.headerSubtitle=b.headerSubtitle,d.closeButton=b.closeButton,d.closeButtonWrapper=b.closeButtonWrapper,d.clearChatButton=b.clearChatButton,d.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{p.footer.replaceWith(b),p.footer=b}}},Oc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Dc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Dc(e,n);return{instance:r,element:r.element}};var jb=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}},Ub=(e,t)=>{if(!e)return null;let n=jb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},zb=(e,t)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},qb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Nc=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Fc=320,Qf=320,Vb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Kb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Gb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Jb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Xb=e=>{if(!e||e.length===0)return null;let t=Fe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Fe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=re(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Fe("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Yb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Fs(o.ref,{readonly:!0,render:t}))}return n},Jf="\uE000",Xf="\uE001",Qb=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${Jf}${r}:${b}${Xf}`,a=t.map((b,f)=>b.kind==="text"?b.text:s(f)).join(""),i=n(a);if(!t.every((b,f)=>b.kind==="text"||i.includes(s(f)))){e.replaceChildren(Yb(t,o));return}e.innerHTML=i;let p=new RegExp(`${Jf}${r}:(\\d+)${Xf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let b=c.nextNode();b;b=c.nextNode())u.push(b);for(let b of u){let f=b;for(let y=p.exec(f.data);y;y=p.exec(f.data)){let C=t[Number(y[1])],k=f.splitText(y.index);k.data=k.data.slice(y[0].length),C?.kind==="mention"&&k.parentNode?.insertBefore(Fs(C.ref,{readonly:!0,render:o}),k),f=k}}},Zb=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,d)=>{let p=m("img");p.alt=i.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${Fc}px`,p.style.maxHeight=`${Qf}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,p.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{c=!0}),qb(i.image)?(p.src=i.image,o.appendChild(p)):(c=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},ev=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Nc(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Fc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},tv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Nc(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Fc}px`,r.style.maxHeight=`${Qf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},nv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Nc(o.data))return;let r=m("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ar=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},_c=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:ar};if(t){let r=t(o);if(r!==null)return r}return ar()},ov=(e,t)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Yf=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},$c=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","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-container","persona-text-persona-text","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-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},jc=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let y=m("div");return y.style.display="none",y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id),y}let i=t.visibility??"hover",d=t.align??"right",p=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[p],b=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let f=(y,C,k)=>{let L=dt({icon:y,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",k),L};return o&&b.appendChild(f("copy","Copy message","copy")),a&&b.appendChild(f("volume-2","Read aloud","read-aloud")),r&&b.appendChild(f("thumbs-up","Upvote","upvote")),s&&b.appendChild(f("thumbs-down","Downvote","downvote")),b},Vr=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",d=a.avatar,p=a.timestamp,c=d?.show??!1,u=p?.show??!1,b=d?.position??"left",f=p?.position??"below",y=$c(e.role,i),C=m("div",y.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=Vb(e),L=e.content?.trim()??"",E=k.length>0&&L===li,P=Wi(s?.widgetConfig?.features?.streamAnimation),_=s?.widgetConfig?.features?.streamAnimation?.plugins,q=e.role==="assistant"&&P.type!=="none"?Ur(P.type,_):null,w=e.role==="assistant"&&q?.isAnimating?.(e)===!0,z=e.role==="assistant"&&q!==null&&(!!e.streaming||w);z&&q?.bubbleClass&&C.classList.add(q.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),z&&q&&(q.containerClass&&V.classList.add(q.containerClass),V.style.setProperty("--persona-stream-step",`${P.speed}ms`),V.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let te=z?Hi(e.content??"",P.buffer,q,e,!!e.streaming):e.content??"",O=()=>{let Z=t({text:te,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&q?.wrap==="char"?Js(Z,"char",e.id,{skipTags:q.skipTags}):z&&q?.wrap==="word"?Js(Z,"word",e.id,{skipTags:q.skipTags}):Z},j=null;if(E?(j=document.createElement("div"),j.innerHTML=O(),j.style.display="none",V.appendChild(j)):e.contentSegments?.length?Qb(V,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=O(),z&&q?.useCaret&&!E&&L){let Z=Bi(),ue=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=ue[ue.length-1];if(xe?.parentNode)xe.parentNode.insertBefore(Z,xe.nextSibling);else{let ye=V.lastElementChild;ye?ye.appendChild(Z):V.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=Yf(e,p,"span");Z.classList.add("persona-timestamp-inline");let ue=V.lastElementChild;ue?ue.appendChild(Z):V.appendChild(Z)}if(k.length>0){let Z=Zb(k,!E&&!!L,()=>{E&&j&&(j.style.display="")});Z?C.appendChild(Z):E&&j&&(j.style.display="")}let Y=Kb(e);if(Y.length>0){let Z=ev(Y);Z&&C.appendChild(Z)}let be=Gb(e);if(be.length>0){let Z=tv(be);Z&&C.appendChild(Z)}let ve=Jb(e);if(ve.length>0){let Z=nv(ve);Z&&C.appendChild(Z)}let Be=e.contentSegments?.length?null:Xb(e.contextMentions);if(Be&&C.appendChild(Be),C.appendChild(V),u&&f==="below"&&e.createdAt){let Z=Yf(e,p);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let se=e.role==="assistant"?Ub(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(te&&te.trim()),ue=P.placeholder==="skeleton",xe=ue&&P.buffer==="line"&&Z;if(Z)xe&&C.appendChild(Xs());else if(ue)C.appendChild(Xs());else{let ye=_c("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&C.appendChild(ye)}}if(se&&e.stopReason&&!e.streaming&&(L||(V.style.display="none"),C.appendChild(zb(e.stopReason,se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=jc(e,o,r);C.appendChild(Z)}if(!c||e.role==="system")return C;let ee=m("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=ov(d,e.role);return b==="right"||b==="left"&&e.role==="user"?ee.append(C,de):ee.append(de,C),ee},Zf=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vr(e,t,n,o,r,s)};var Kr=new Set,rv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sv=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
42
|
-
`):""},
|
|
43
|
-
`);let r=
|
|
44
|
-
`):""},zc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},lv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=iv(e,o?.previewMaxLines??3),a=n?wu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=t?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),i&&d.activeTextTemplate?p=lc(n,d.activeTextTemplate,p):!i&&d.completeTextTemplate&&(p=lc(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:i}},tg=(e,t,n)=>{let o=Gr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let p=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(p){p.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=re(o?"chevron-up":"chevron-down",16,c,2);u?p.appendChild(u):p.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},qc=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:p,isActive:c}=lv(e,t),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let b=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),C=()=>{let O=m("span","");return O.setAttribute("data-tool-elapsed",y),O.textContent=Hs(n),O},k=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Hs(n),createElapsedElement:C});typeof k=="string"&&k.trim()?(f.textContent=k,b.appendChild(f)):k instanceof HTMLElement?b.appendChild(k):(f.textContent=d,b.appendChild(f));let L=s.loadingAnimation??"none",H=o.activeTextTemplate,E=o.completeTextTemplate,P=c?H:E,_=k instanceof HTMLElement,q=(O,j)=>{f.textContent="";let Y=n.name?.trim()||"tool",be=ni(O,Y),ve=0;for(let Be of be){let se=Be.styles.length>0?(()=>{let he=m("span",Be.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(he),he})():f;if(Be.isDuration&&c)se.appendChild(C());else{let he=Be.isDuration?Hs(n):Be.text;j?ve=Po(se,he,ve):se.appendChild(document.createTextNode(he))}}};if(!_)if(c&&L!=="none"){let O=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),P&&q(P,!1);else if(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),P)q(P,!0);else{let j=f.textContent||d;f.textContent="",Po(f,j,0)}}else P&&q(P,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",j=re(i?"chevron-up":"chevron-down",16,O,2);j?w.appendChild(j):w.textContent=i?"Hide":"Show";let Y=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(w),u.append(b,Y)}else u.append(b);let z=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&p){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:c,config:t??{}});av(z,O)||(z.textContent=p),z.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,z),r;let V=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=i?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let O=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,V.appendChild(O)}if(n.args!==void 0){let O=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Arguments";let Y=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",zc(Y,o),Y.textContent=wo(n.args),O.append(j,Y),V.appendChild(O)}if(n.chunks&&n.chunks.length){let O=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Activity";let Y=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",zc(Y,o),Y.textContent=n.chunks.join(""),O.append(j,Y),V.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Result";let Y=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",zc(Y,o),Y.textContent=wo(n.result),O.append(j,Y),V.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,V.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",j=re(i?"chevron-up":"chevron-down",16,O,2);j?w.appendChild(j):w.textContent=i?"Hide":"Show"}V.style.display=i?"":"none",z.style.display=i?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(u,z,V),r};var ir=new Map,Vi=e=>{let n=(e.startsWith(Sn)?e.slice(Sn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ng=e=>e?.approval!==!1?e?.approval:void 0,og=(e,t)=>{let n=ng(t)?.detailsDisplay??"collapsed";return ir.get(e)??n==="expanded"},rg=(e,t,n)=>{let o=ng(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=re(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},sg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=og(e,n);rg(o,s,n),r.style.display=s?"":"none"};var Ki=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",p=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=re(d,20,p,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),b=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",b.appendChild(f),!r){let w=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),b.appendChild(w)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(Sn)?Es(n.toolName):void 0,k=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,H=k||(L?n.description:`The assistant wants to use \u201C${C??Vi(n.toolName)}\u201D.`),E=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=H,u.appendChild(E),n.reason){let w=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let z=m("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(z),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let P=o?.detailsDisplay??"collapsed",_=!!n.description&&!L,q=_||!!n.parameters;if(P!=="hidden"&&q){let w=og(e.id,t),z=m("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=m("span");V.setAttribute("data-approval-details-label","true");let te=m("span","persona-inline-flex persona-items-center");te.setAttribute("data-approval-details-chevron","true"),z.append(V,te),rg(z,w,t),u.appendChild(z);let O=m("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",_){let j=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,O.appendChild(j)}if(n.parameters){let j=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(j.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=wo(n.parameters),O.appendChild(j)}u.appendChild(O)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let z=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let V=re("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",z.appendChild(V));let te=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(te);let O=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let j=re("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);j&&(j.style.marginRight="4px",O.appendChild(j));let Y=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(Y),w.append(z,O),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function cv(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function ag(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:d=2147483e3,onOpen:p,onDismiss:c}=e,u=e.container??cv(t),b=!1,f=null,y=()=>{if(!b)return;let L=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${L.width}px`),a&&(n.style.maxWidth=`${L.width}px`);let H=n.getBoundingClientRect(),E=i?.()??null,P=E!=null?L.top+E:L.top,_=o==="top-start"||o==="top-end"?P-r-H.height:L.bottom+r,w=o==="bottom-end"||o==="top-end"?L.right-H.width:L.left,z=a?.()??null;if(z!=null){let V=Math.max(L.left,L.right-H.width);w=Math.min(Math.max(L.left+z,L.left),V)}n.style.top=`${_}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},k=()=>{if(b)return;b=!0,d!=null&&(n.style.zIndex=String(d)),u.appendChild(n),y();let L=(t.ownerDocument??document).defaultView??window,H=t.ownerDocument??document,E=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}y()},P=q=>{let w=typeof q.composedPath=="function"?q.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},_=L.setTimeout(()=>{H.addEventListener("pointerdown",P,!0)},0);L.addEventListener("scroll",E,!0),L.addEventListener("resize",E),f=()=>{L.clearTimeout(_),H.removeEventListener("pointerdown",P,!0),L.removeEventListener("scroll",E,!0),L.removeEventListener("resize",E)},p?.()};return{get isOpen(){return b},open:k,close:C,toggle:()=>b?C():k(),reposition:y,destroy:C}}function ig(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var dv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),lg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},lr=(e,t)=>{lg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},pv=e=>e?.approval!==!1?e?.approval:void 0,uv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return ir.get(e)??n==="expanded"},Vc=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},fv=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Sn)?Es(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Vi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let p=document.createElement("strong");p.textContent=i,n.appendChild(p)}return n},gv=e=>{let t=m("div","persona-approval-resolved"),n=re("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?Vi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},mv=(e,t,n,o,r,s,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",p=!!n.description&&d!=="hidden",c=n.parameters!=null&&d!=="hidden",u=p||c,b=u&&uv(t.id,o),f=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?y:f)):C.setAttribute("data-static","true");let k=m("span","persona-approval-logo"),L=re("shield-check",16,"currentColor",2);L&&k.appendChild(L),C.appendChild(k);let H=fv(n,o);if(u){let z=m("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let V=re("chevron-down",14,"currentColor",2);V&&z.appendChild(V),H.append(" "),H.appendChild(z)}C.appendChild(H),i.appendChild(C);let E=m("div","persona-approval-body");if(u){let z=m("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!b,p){let V=m("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,z.appendChild(V)}if(c){let V=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=wo(n.parameters),z.appendChild(V)}E.appendChild(z)}if(n.reason){let z=m("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=m("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(V,document.createTextNode(n.reason)),E.appendChild(z)}let P=m("div","persona-approval-actions"),_=null,q=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},w=m("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),a){let z=m("div","persona-approval-split"),V=m("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),q(V),V.append(o?.approveLabel??"Always allow",Vc("\u23CE"));let te=m("button","persona-approval-caret");te.type="button",te.setAttribute("data-action","toggle-menu"),te.setAttribute("aria-label","More options"),q(te);let O=re("chevron-down",15,"currentColor",2);O&&te.appendChild(O),z.append(V,te),P.append(z,w),w.append(Vc("Esc"));let j=m("div","persona-approval-menu"),Y=m("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",Vc("\u2318\u23CE")),j.appendChild(Y),_=ag({anchor:z,content:j,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,_),Y.addEventListener("click",()=>{lr(e,t.id),r()})}else{let z=m("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),q(z),z.append(o?.approveLabel??"Allow"),P.append(z,w)}return E.appendChild(P),i.appendChild(E),i.addEventListener("click",z=>{let V=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!V)return;let te=V.getAttribute("data-action");if(te==="toggle-params"){let O=i.querySelector('[data-role="params"]');if(O){let j=O.hidden;O.hidden=!j,C.setAttribute("aria-expanded",j?"true":"false"),C.setAttribute("aria-label",j?y:f),ir.set(t.id,j)}return}if(te==="toggle-menu"){_?.toggle();return}if(te==="always"){lr(e,t.id),r({remember:!0});return}if(te==="allow"){lr(e,t.id),r();return}if(te==="deny"){lr(e,t.id),s();return}}),i},cg=()=>{let e=dv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let d=pv(a);if(i.status!=="pending"){if(lr(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return gv(i)}lg(e,o.id);let p=d?.enableAlwaysAllow===!0,c=mv(e,o,i,d,r,s,p);if(p){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=b=>{ig(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),lr(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])lr(e,o);e.latestPendingApprovalId=null}}};var dg=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,d,p)=>{e.innerHTML="",t.length=0;let c=p?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(i??(s?s.getMessages():[])).some(k=>k.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,f=y=>{switch(y){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(y=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=y,C.disabled=b,d?.fontFamily&&(C.style.fontFamily=f(d.fontFamily)),d?.fontWeight&&(C.style.fontWeight=d.fontWeight),d?.paddingX&&(C.style.paddingLeft=d.paddingX,C.style.paddingRight=d.paddingX),d?.paddingY&&(C.style.paddingTop=d.paddingY,C.style.paddingBottom=d.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let y=JSON.stringify(r);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Zs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ea=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var hv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),yv=new Set(["step_start","execution_start"]),bv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),vv=new Set(["step_complete","agent_turn_complete"]),xv=new Set(["flow_complete","agent_complete"]),pg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),fg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,cr=(e,t)=>{let n=e[t];return fg(n)?n:void 0};function Kc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Gi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Cv(e,t){return typeof t.type=="string"?t.type:e}function wv(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 Av(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 ug(e){let t=cr(e,"result"),n=[cr(e,"tokens"),cr(e,"totalTokens"),t?cr(t,"tokens"):void 0,cr(e,"usage"),t?cr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(e.outputTokens)??cn(e.completionTokens)??(t?cn(t.outputTokens)??cn(t.completionTokens):void 0)}function Sv(e){let t=cr(e,"result");return cn(e.executionTime)??cn(e.executionTimeMs)??cn(e.execution_time)??cn(e.duration)??(t?cn(t.executionTime)??cn(t.executionTimeMs):void 0)}function Tv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ta=class{constructor(t=Tv){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:Gi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!fg(n)){pg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Cv(t,n),r=this.now();if(hv.has(o)){this.startRun(r);return}if(yv.has(o)){this.run||this.startRun(r);return}if(bv.has(o)){if(!Av(o,n))return;let s=wv(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+Kc(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Gi(i,d),outputTokens:i,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(vv.has(o)){if(!this.run)return;let s=this.run,a=ug(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,d=s.exactOutputTokens+Kc(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Gi(d,p),outputTokens:d,durationMs:p,source:i?"usage":"estimate"};return}if(xv.has(o)){if(!this.run)return;let s=this.run,a=ug(n),i=a??s.exactOutputTokens+Kc(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Gi(i,p),outputTokens:i,durationMs:p,source:d},this.run=null;return}if(pg.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Sv(n)??o-t.startedAt}};function Jr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Mv={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)"}},Ev={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},kv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pv=100;function Lv(e,t){let n={...Mv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ev}function Rv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Iv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Wv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Hv(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Bv(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 Dv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ov(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 Nv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Gc(e,t,n,o,r,s,a,i){let d=r.has(e.id),p=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Jr(p,o.classNames?.eventRow);let c=a.find(b=>b.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let b=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(b)return p.appendChild(b),p}return p.appendChild(u()),p;function u(){let b=m("div",""),f=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let y=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=re(d?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let k=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";k.textContent=L==="relative"?Rv(e.timestamp,n):Iv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let E=Lv(e.type,o.badgeColors),P=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=E.bg,P.style.color=E.text,P.style.borderColor=E.text+"50",P.textContent=e.type;let _=o.descriptionFields??kv,q=Wv(e.payload,_),w=null;q&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=q);let z=m("div","persona-flex-1 persona-min-w-0"),V=m("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),te=re("clipboard","12px","currentColor",1.5);return te&&V.appendChild(te),V.addEventListener("click",async O=>{O.stopPropagation(),await Hv(Bv(e)),V.innerHTML="";let j=re("check","12px","currentColor",1.5);j&&V.appendChild(j),setTimeout(()=>{V.innerHTML="";let Y=re("clipboard","12px","currentColor",1.5);Y&&V.appendChild(Y)},1500)}),f.appendChild(y),f.appendChild(k),H&&f.appendChild(H),f.appendChild(P),w&&f.appendChild(w),f.appendChild(z),f.appendChild(V),b.appendChild(f),d&&b.appendChild(Nv(e,a,i)),b}}function gg(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,d=i?.enabled!==!1,p=i?.iconName??"arrow-down",c=i?.label??"",u=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return f();function f(){let y=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Jr(C,y?.panel);let k=[],L="",H="",E=null,P=[],_={},q=0,w=Li(),z=0,V=0,te=!1,O=null,j=!1,Y=0,be=new Set,ve=new Map,Be="",se="",he=null,ee,de,Z,ue,xe=null,ye=null,Se=null;function lt(){let D=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),U=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Jr(U,y?.headerBar),a){ye=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",xe=m("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),xe.textContent="-- tok/s",Se=m("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Se.style.display="none",Se.style.pointerEvents="none";let _e=ye,Dt=Se,ml=()=>{if(!Dt.textContent)return;let pa=_e.getBoundingClientRect(),ua=D.getBoundingClientRect();Dt.style.left=`${pa.left-ua.left}px`,Dt.style.top=`${pa.bottom-ua.top+4}px`,Dt.style.display="block"},Do=()=>{Dt.style.display="none"};ye.addEventListener("mouseenter",ml),ye.addEventListener("mouseleave",Do),ye.appendChild(xe)}let Q=m("div","persona-flex-1");ee=m("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ge=m("option","");Ge.value="",Ge.textContent="All events (0)",ee.appendChild(Ge),de=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let Ye=re("clipboard-copy","12px","currentColor",1.5);Ye&&de.appendChild(Ye);let rt=m("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",de.appendChild(rt),ye&&U.appendChild(ye),U.appendChild(Q),U.appendChild(ee),U.appendChild(de);let K=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Jr(K,y?.searchBar);let Ue=re("search","14px","var(--persona-muted, #9ca3af)",1.5),Ce=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ue&&Ce.appendChild(Ue),Z=m("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Jr(Z,y?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",ue=m("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ue.type="button",ue.style.display="none";let ze=re("x","12px","currentColor",2);return ze&&ue.appendChild(ze),K.appendChild(Ce),K.appendChild(Z),K.appendChild(ue),D.appendChild(U),D.appendChild(K),Se&&D.appendChild(Se),D}let Ee,De=s.find(D=>D.renderEventStreamToolbar);De?.renderEventStreamToolbar&&r?Ee=De.renderEventStreamToolbar({config:r,defaultRenderer:()=>lt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:U=>{L=U,et(),ie()},onSearchChange:U=>{H=U,et(),ie()}})??lt():Ee=lt();let Ne=m("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function qe(){if(!a||!xe||!ye)return;let D=a(),U=Dv(D);xe.textContent=U;let Q=Ov(D);Se&&(Se.textContent=Q,Q||(Se.style.display="none")),ye.setAttribute("aria-label",Q?`Throughput: ${U}, ${Q}`:`Throughput: ${U}`)}let Me=m("div","persona-flex-1 persona-min-h-0 persona-relative"),ce=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ce.style.height="100%";let Le=m("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Jr(Le,y?.scrollIndicator),Le.style.display="none",Le.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let st=re(p,"14px","currentColor",2);st&&Le.appendChild(st);let xt=m("span","");xt.textContent=c,Le.appendChild(xt);let Lt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Lt.style.display="none",Me.appendChild(ce),Me.appendChild(Lt),Me.appendChild(Le),C.setAttribute("tabindex","0"),C.appendChild(Ee),C.appendChild(Ne),C.appendChild(Me);function Tt(){let D=t.getAll(),U={};for(let K of D)U[K.type]=(U[K.type]||0)+1;let Q=Object.keys(U).sort(),Ge=Q.length!==P.length||!Q.every((K,Ue)=>K===P[Ue]),We=!Ge&&Q.some(K=>U[K]!==_[K]),Ye=D.length!==Object.values(_).reduce((K,Ue)=>K+Ue,0);if(!Ge&&!We&&!Ye||(P=Q,_=U,!ee))return;let rt=ee.value;if(ee.options[0].textContent=`All events (${D.length})`,Ge){for(;ee.options.length>1;)ee.remove(1);for(let K of Q){let Ue=m("option","");Ue.value=K,Ue.textContent=`${K} (${U[K]||0})`,ee.appendChild(Ue)}rt&&Q.includes(rt)?ee.value=rt:rt&&(ee.value="",L="")}else for(let K=1;K<ee.options.length;K++){let Ue=ee.options[K];Ue.textContent=`${Ue.value} (${U[Ue.value]||0})`}}function Oe(){let D=t.getAll();if(L&&(D=D.filter(U=>U.type===L)),H){let U=H.toLowerCase();D=D.filter(Q=>Q.type.toLowerCase().includes(U)||Q.payload.toLowerCase().includes(U))}return D}function pe(){return L!==""||H!==""}function et(){q=0,z=0,w.resume(),Le.style.display="none"}function Ie(D){be.has(D)?be.delete(D):be.add(D),he=D;let U=ce.scrollTop,Q=w.isFollowing();j=!0,w.pause(),ie(),ce.scrollTop=U,Q&&w.resume(),j=!1}function ge(){return Io(ce,50)}function ie(){V=Date.now(),te=!1,qe(),Tt();let D=t.getEvictedCount();D>0?(Ne.textContent=`${D.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",k=Oe();let U=k.length,Q=t.getSize()>0;U===0&&Q&&pe()?(Lt.textContent=H?`No events matching '${H}'`:"No events matching filter",Lt.style.display="",ce.style.display="none"):(Lt.style.display="none",ce.style.display=""),de&&(de.title=pe()?`Copy Filtered (${U})`:"Copy All"),d&&!w.isFollowing()&&U>q&&(z+=U-q,xt.textContent=c?`${c}${z>0?` (${z})`:""}`:"",Le.style.display=""),q=U;let Ge=t.getAll(),We=Ge.length>0?Ge[0].timestamp:0,Ye=new Set(k.map(Ue=>Ue.id));for(let Ue of be)Ye.has(Ue)||be.delete(Ue);let rt=L!==Be||H!==se,K=ve.size===0&&k.length>0;if(rt||K||k.length===0){ce.innerHTML="",ve.clear();let Ue=document.createDocumentFragment();for(let Ce=0;Ce<k.length;Ce++){let ze=Gc(k[Ce],Ce,We,u,be,Ie,s,r);ve.set(k[Ce].id,ze),Ue.appendChild(ze)}ce.appendChild(Ue),Be=L,se=H,he=null}else{if(he!==null){let Ce=ve.get(he);if(Ce&&Ce.parentNode===ce){let ze=k.findIndex(_e=>_e.id===he);if(ze>=0){let _e=Gc(k[ze],ze,We,u,be,Ie,s,r);ce.insertBefore(_e,Ce),Ce.remove(),ve.set(he,_e)}}he=null}let Ue=new Set(k.map(Ce=>Ce.id));for(let[Ce,ze]of ve)Ue.has(Ce)||(ze.remove(),ve.delete(Ce));for(let Ce=0;Ce<k.length;Ce++){let ze=k[Ce];if(!ve.has(ze.id)){let _e=Gc(ze,Ce,We,u,be,Ie,s,r);ve.set(ze.id,_e),ce.appendChild(_e)}}}w.isFollowing()&&(ce.scrollTop=ce.scrollHeight)}function Re(){if(Date.now()-V>=Pv){O!==null&&(cancelAnimationFrame(O),O=null),ie();return}te||(te=!0,O=requestAnimationFrame(()=>{O=null,ie()}))}let ct=(D,U)=>{if(!de)return;de.innerHTML="";let Q=re(D,"12px","currentColor",1.5);Q&&de.appendChild(Q);let Ge=m("span","persona-text-xs");Ge.textContent="Copy All",de.appendChild(Ge),setTimeout(()=>{de.innerHTML="";let We=re("clipboard-copy","12px","currentColor",1.5);We&&de.appendChild(We);let Ye=m("span","persona-text-xs");Ye.textContent="Copy All",de.appendChild(Ye),de.disabled=!1},U)},fe=async()=>{if(de){de.disabled=!0;try{let D;pe()?D=k:n?(D=await n(),D.length===0&&(D=t.getAll())):D=t.getAll();let U=D.map(Q=>{try{return JSON.parse(Q.payload)}catch{return Q.payload}});await navigator.clipboard.writeText(JSON.stringify(U,null,2)),ct("check",1500)}catch{ct("x",1500)}}},Ae=()=>{ee&&(L=ee.value,et(),ie())},ne=()=>{!Z||!ue||(ue.style.display=Z.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{H=Z.value,et(),ie()},150))},T=()=>{!Z||!ue||(Z.value="",H="",ue.style.display="none",E&&clearTimeout(E),et(),ie())},N=()=>{if(j)return;let D=ce.scrollTop,{action:U,nextLastScrollTop:Q}=Ri({following:w.isFollowing(),currentScrollTop:D,lastScrollTop:Y,nearBottom:ge(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Y=Q,U==="resume"?(w.resume(),z=0,Le.style.display="none"):U==="pause"&&(w.pause(),d&&(xt.textContent=c,Le.style.display=""))},v=D=>{let U=Ii({following:w.isFollowing(),deltaY:D.deltaY,nearBottom:ge(),resumeWhenNearBottom:!0});U==="pause"?(w.pause(),d&&(xt.textContent=c,Le.style.display="")):U==="resume"&&(w.resume(),z=0,Le.style.display="none")},I=()=>{d&&(ce.scrollTop=ce.scrollHeight,w.resume(),z=0,Le.style.display="none")},M=D=>{let U=D.target;if(!U||U.closest("button"))return;let Q=U.closest("[data-event-id]");if(!Q)return;let Ge=Q.getAttribute("data-event-id");Ge&&Ie(Ge)},W=D=>{if((D.metaKey||D.ctrlKey)&&D.key==="f"){D.preventDefault(),Z?.focus(),Z?.select();return}D.key==="Escape"&&(Z&&document.activeElement===Z?(T(),Z.blur(),C.focus()):o&&o())};de&&de.addEventListener("click",fe),ee&&ee.addEventListener("change",Ae),Z&&Z.addEventListener("input",ne),ue&&ue.addEventListener("click",T),ce.addEventListener("scroll",N),ce.addEventListener("wheel",v,{passive:!0}),ce.addEventListener("click",M),Le.addEventListener("click",I),C.addEventListener("keydown",W);function G(){E&&clearTimeout(E),O!==null&&(cancelAnimationFrame(O),O=null),te=!1,ve.clear(),de&&de.removeEventListener("click",fe),ee&&ee.removeEventListener("change",Ae),Z&&Z.removeEventListener("input",ne),ue&&ue.removeEventListener("click",T),ce.removeEventListener("scroll",N),ce.removeEventListener("wheel",v),ce.removeEventListener("click",M),Le.removeEventListener("click",I),C.removeEventListener("keydown",W)}return{element:C,update:Re,destroy:G}}}function Ji(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},d=u=>{let b=u;return s.findIndex(f=>f===b||f.contains(b))},p=u=>{let b=d(u.target);if(b<0)return;let f=b;if(u.key===r)f=Math.min(b+1,s.length-1);else if(u.key===o)f=Math.max(b-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==b&&t.onSelect(f)},c=u=>{let b=d(u.target);b>=0&&i(s[b])};return e.addEventListener("keydown",p),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((f,y)=>{f.setAttribute("role","tab");let C=y===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&y===0?0:-1}),a){let f=(b>=0?u[b]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",c)}}}function mg(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),p=ne=>({start:ne===!1?!1:typeof ne=="object"&&ne?ne.start!==!1:!0,end:ne===!1?!1:typeof ne=="object"&&ne?ne.end!==!1:!0}),{start:c,end:u}=p(n?.tabFade),b=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),j?.hide()};b&&b.addEventListener("click",()=>{f(),t.onDismiss?.()});let y=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let k=m("span","persona-text-xs persona-font-medium persona-truncate");k.textContent=s;let L=dt({icon:"x",label:a});L.addEventListener("click",()=>{f(),t.onDismiss?.()});let H="rendered",E=Qn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ne=>{H=ne==="source"?"source":"rendered",ct()}}),P=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=n?.documentToolbarShowCopyLabel===!0,q=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,z=!!(q&&w&&w.length>0),V=null,te,O=null,j=null;if(r&&(_||q)&&!z){if(te=_?Yn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),q){let ne=re("chevron-down",14,"currentColor",2);ne&&te.appendChild(ne)}}else r&&z?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),te=_?Yn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=dt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),V.append(te,O)):r?te=dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(te=dt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&te.classList.add("persona-hidden"));let Y=r?dt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):dt({icon:"refresh-cw",label:"Refresh"}),be=r?dt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):dt({icon:"x",label:a}),ve=dt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&ve.classList.add("persona-hidden");let Be=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),se=e.features?.artifacts?.toolbarActions??[],he=()=>{let ne=Me.find(I=>I.id===ce)??Me[Me.length-1],T=ne?.id??null,N=ne?.artifactType==="markdown"?ne.markdown??"":"",v=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:N,jsonPayload:v,id:T}},ee=async()=>{let ne=Me.find(T=>T.id===ce)??Me[Me.length-1];try{await navigator.clipboard.writeText(Vs(ne))}catch{}};if(te.addEventListener("click",async()=>{let ne=n?.onDocumentToolbarCopyMenuSelect;if(ne&&z){let{markdown:T,jsonPayload:N,id:v}=he();try{await ne({actionId:"primary",artifactId:v,markdown:T,jsonPayload:N})}catch{}return}await ee()}),O&&w?.length){let ne=()=>y.closest("[data-persona-root]")??document.body,T=()=>{j=Lo({items:w.map(N=>({id:N.id,label:N.label})),onSelect:async N=>{let{markdown:v,jsonPayload:I,id:M}=he(),W=n?.onDocumentToolbarCopyMenuSelect;try{W?await W({actionId:N,artifactId:M,markdown:v,jsonPayload:I}):N==="markdown"||N==="md"?await navigator.clipboard.writeText(v):N==="json"||N==="source"?await navigator.clipboard.writeText(I):await navigator.clipboard.writeText(v||I)}catch{}},anchor:V??O,position:"bottom-right",portal:ne()})};y.isConnected?T():requestAnimationFrame(T),O.addEventListener("click",N=>{N.stopPropagation(),j?.toggle()})}Y.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ct()}),be.addEventListener("click",()=>{f(),t.onDismiss?.()});let de=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),V?P.append(V,Y,be):P.append(te,Y,be),P.insertBefore(Be,be),P.insertBefore(ve,be),C.append(E.element,de,P);else{let ne=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ne.append(te,Be,ve,L),C.appendChild(k),C.appendChild(ne)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Z=m("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");d&&Z.style.setProperty("--persona-artifact-tab-fade-size",d);let ue=e.features?.artifacts?.renderTabBar,xe=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Ji(Z,{onSelect:ne=>t.onSelect(Me[ne].id)}),Se=ne=>{let T=ne.scrollWidth-ne.clientWidth,N=T>1,v=Math.abs(ne.scrollLeft);ne.classList.toggle("persona-artifact-tab-fade-start",c&&N&&v>1),ne.classList.toggle("persona-artifact-tab-fade-end",u&&N&&v<T-1)},lt=0,Ee=()=>{if(lt)return;let ne=()=>{lt=0,Se(Z)};lt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ne):setTimeout(ne,0)};Z.addEventListener("scroll",()=>Ee(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Se(Z)).observe(Z);let De=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ne=()=>{De.scrollLeft=0},qe=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ne):setTimeout(Ne,0)};if(i){for(let ne of[Z,xe])ne.style.paddingLeft=i,ne.style.paddingRight=i;De.style.padding=i}y.appendChild(C),y.appendChild(Z),y.appendChild(xe),y.appendChild(De);let Me=[],ce=null,Le=!1,st=!1,xt=!0,Lt=!1,Tt=null,Oe="",pe=null,et=!1,Ie=ne=>ne.artifactType==="markdown"&&!!ne.file||r?H:"rendered",ge=ne=>{r||(ne&&!et?(C.insertBefore(E.element,k),et=!0):!ne&&et&&(E.element.remove(),et=!1))},ie=()=>ce&&Me.find(ne=>ne.id===ce)||Me[Me.length-1],Re=()=>{let ne=zs(ie());if(!ne){Be.replaceChildren();return}let T=se.filter(N=>N.visible===void 0||N.visible(ne)).map(N=>jr(N,{documentChrome:r,onClick:()=>{let v=zs(ie());if(v)try{Promise.resolve(N.onClick(v)).catch(()=>{})}catch{}}}));Be.replaceChildren(...T)},ct=()=>{Re();let ne=r&&Me.length<=1,T=!!ue;if(Z.classList.toggle("persona-hidden",ne||T),xe.classList.toggle("persona-hidden",ne||!T),T&&ue){let I=Me.map(M=>M.id).join("|")+" "+(ce??"");if(I!==Oe){Oe=I;let M=ue({records:Me,selectedId:ce,onSelect:t.onSelect});xe.firstElementChild!==M&&xe.replaceChildren(M)}}else{ye.beforeRender(),Z.replaceChildren();let I=[],M=-1;for(let[W,G]of Me.entries()){let D=m("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");D.type="button";let U=G.artifactType==="markdown"?G.file:void 0,Q=U?Wn(U.path):G.title||G.id.slice(0,8),Ge=U?.path||G.title||Q;D.textContent=Q,D.title=Ge,D.setAttribute("aria-label",Ge),G.id===ce&&(D.classList.add("persona-bg-persona-container","persona-border-persona-border"),M=W),D.addEventListener("click",()=>t.onSelect(G.id)),Z.appendChild(D),I.push(D)}if(ye.render(I,M),M>=0&&ce!==Tt){Tt=ce;let W=I[M];typeof W.scrollIntoView=="function"&&W.scrollIntoView({block:"nearest",inline:"nearest"})}Se(Z)}let N=ce&&Me.find(I=>I.id===ce)||Me[Me.length-1];if(!N){De.replaceChildren(),pe=null,ge(!1);return}let v=N.artifactType==="markdown"?N.file:void 0;if(ge(!!v),r){let I=v?ko(v):N.artifactType==="markdown"?"MD":N.component??"Component",M=(N.title||"Document").trim(),W=v?Wn(v.path):M.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${W} \xB7 ${I}`}else k.textContent=v?Wn(v.path):s;pe?(pe.el.parentElement!==De&&De.replaceChildren(pe.el),pe.update(N)):(pe=ki(N,{config:e,resolveViewMode:Ie}),De.replaceChildren(pe.el)),De.classList.toggle("persona-artifact-content-flush",!!De.querySelector(".persona-code-pre"))},fe=()=>{let ne=Me.length>0;if(y.classList.toggle("persona-hidden",!ne),b){let v=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ne&&v&&Le?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},Ae=()=>{Lt=!1,ct(),fe()};return{element:y,backdrop:b,update(ne){let T=ne.selectedId??ne.artifacts[ne.artifacts.length-1]?.id??null,N=T!==ce;Me=ne.artifacts,ce=T,Me.length>0&&(Le=!0),Lt=!0,xt&&Ae(),N&&Ne()},setMobileOpen(ne){Le=ne,!ne&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):fe()},setExpanded(ne){ne!==st&&(st=ne,qe());let T=re(ne?"minimize":"maximize",16,"currentColor",2);T&&ve.replaceChildren(T);let N=ne?"Collapse artifacts panel":"Expand artifacts panel";ve.setAttribute("aria-label",N),ve.title=N},setExpandToggleVisible(ne){ve.classList.toggle("persona-hidden",!ne)},setCopyButtonVisible(ne){r||te.classList.toggle("persona-hidden",!ne)},setCustomActions(ne){se=ne,Re()},setTabFade(ne){let T=p(ne);T.start===c&&T.end===u||(c=T.start,u=T.end,Se(Z))},setRenderTabBar(ne){ne!==ue&&(ue=ne,Oe="",ct())},setVisible(ne){ne!==xt&&(xt=ne,ne&&Lt&&Ae())}}}function Yt(e){return e?.features?.artifacts?.enabled===!0}function hg(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Yt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Fv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var yg=["panel","seamless","detached"];function Jc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&yg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Xc(e){return!e||!Yt(e)?!1:Jc(e)==="detached"}function na(e,t){if(!Yt(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"),Fv(e),hg(e,t);return}let n=t.features?.artifacts?.layout,o=Jc(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let d=n?.documentToolbarToggleActiveBorderColor?.trim();d?e.style.setProperty("--persona-artifact-doc-toggle-active-border",d):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),hg(e,t)}function oa(e,t){for(let i of yg)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Yt(t))return;let n=t.features?.artifacts?.layout,o=Jc(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function bg(e,t){return!t||!Yt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var _v=new Set(["__proto__","prototype","constructor"]),$v=new Set(["collapsed","card","panel","inline"]),vg=new Set(["markdown","component"]),jv=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,dr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yi=e=>!_v.has(e),Yc=e=>typeof e=="string"&&$v.has(e),pr=e=>Object.keys(e).length>0;function Bn(e,t,n,o){e.push({path:t,code:n,message:o})}var Uv="Ignored because this key is not part of the persisted preference schema.",Xi="Ignored an unsupported value.",zv="Expected collapsed, panel, or inline.",qv='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',xg={kind:"mode",message:Xi},Xr={kind:"string",message:"Expected a CSS length string."},eo={kind:"boolean"},Vv={paneWidth:Xr,paneMaxWidth:Xr,paneMinWidth:Xr,expandedPanelWidth:Xr,resizableMinWidth:Xr,resizableMaxWidth:Xr,expandLauncherPanelWhenOpen:eo,resizable:eo},Kv={kind:"object",message:"Expected a preference object.",children:{showToolCalls:eo,showReasoning:eo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Xi},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Xi},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Xi},expandable:eo,grouped:eo}},reasoningDisplay:{kind:"object",children:{expandable:eo,activePreview:eo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:xg,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:xg,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:vg,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:vg}}},filePreview:{kind:"object",children:{enabled:eo}},layout:{kind:"object",children:Vv}}}}};function Cg(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Bn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Bn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Bn(o,n,"invalid_value",t.message);case"mode":return Yc(e)?en(e):Bn(o,n,"invalid_value",t.message);case"modeMap":{if(!dr(e))return Bn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,i]of Object.entries(e)){let d=r?a:yo(a);Yi(a)&&(r?r.has(a):jv.test(d))?Yc(i)?s[d]=en(i):Bn(o,`${n}.${a}`,"invalid_value",zv):Bn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":qv)}return pr(s)?s:void 0}case"object":{if(t.bareMode&&Yc(e))return en(e);if(!dr(e))return Bn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=i=>n?`${n}.${i}`:i;for(let i of Object.keys(e))(!Yi(i)||!r.includes(i))&&Bn(o,s(i),"unknown_key",Uv);let a={};for(let i of r){let d=t.children[i],p=Cg(e[i],d,s(i),o);if(d.deprecated&&e[i]!==void 0&&Bn(o,s(i),"deprecated_key",d.deprecated),p===void 0)continue;let c=d.alias??i,u=a[c];a[c]=dr(u)&&dr(p)?{...u,...p}:p}return pr(a)?a:void 0}}}function Qc(e){let t=[];return{preferences:(e===null?void 0:Cg(e,Kv,"",t))??{},issues:t}}function Yr(e){if(Array.isArray(e))return e.map(Yr);if(!dr(e))return e;let t={};for(let[n,o]of Object.entries(e))Yi(n)&&o!==void 0&&(t[n]=Yr(o));return t}function wg(e,t){let n=Yr(e);for(let[o,r]of Object.entries(t)){if(!Yi(o)||r===void 0)continue;let s=n[o];n[o]=dr(s)&&dr(r)?wg(s,r):Yr(r)}return n}function Gv(e){let t={},n;for(let r of e){let s=Qc(r).preferences;n=Ag(n,s.artifacts?.display),t=wg(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Jv(e,t){if(t===void 0)return e===void 0?void 0:Yr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...pr(r)?{byMediaType:r}:{}};return pr(s)?s:void 0}function Ag(e,t){if(t===void 0)return e===void 0?void 0:Yr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Jv(n.files,t.files),a={...o?{default:o}:{},...pr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return pr(a)?a:void 0}function Zc(e={},t){let n=Gv(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Ag(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function ra(e){let t=e.preferences;return!t||!pr(t)?e:{...e,features:Zc(e.features??{},[t])}}function Xv(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Yv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Qv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Zv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function ed(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Sg(e,t,n,o,r,s){let a=Xv(r,200),i=Zv(t,n,o,200);i=Math.max(a,i);let d=Yv(s);return d!==null&&(i=Math.min(i,d)),Qv(e,a,i)}var Tg={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"}},td=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=Tg[a]??Tg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=m("div","persona-space-y-1"),p=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=i.title,d.appendChild(p),i.description){let y=m("p","persona-text-sm persona-text-persona-muted");y.textContent=i.description,d.appendChild(y)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(y=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${y.name}`;let k=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=y.label,C.appendChild(k);let L=y.type??"text",H;L==="textarea"?(H=document.createElement("textarea"),H.rows=3):(H=document.createElement("input"),H.type=L),H.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",H.id=`${t.id}-${a}-${y.name}`,H.name=y.name,H.placeholder=y.placeholder??"",y.required&&(H.required=!0),C.appendChild(H),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(b),u.appendChild(f),c.appendChild(u),s.replaceChildren(d,c),c.addEventListener("submit",async y=>{y.preventDefault();let C=n.formEndpoint??"/form",k=new FormData(c),L={};k.forEach((H,E)=>{L[E]=H}),L.type=a,f.disabled=!0,b.textContent="Submitting\u2026";try{let H=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let E=await H.json();b.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(H){b.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var nd=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},sa=new nd;var Mg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ex=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Eg=(e,t,n)=>{if(!Mg(e)||!Mg(t)||ex.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Eg(e[r],t[r],s)}return o};function Qi(e,t){let n=Eg(e,t,"");return Nr(n)}var kg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var tx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},nx=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},aa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=tx(e),n=nx(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},od=e=>typeof e=="string"?e:e==null?"":String(e),ur={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:od(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=od(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:od(n.text)}}},Pg=e=>Array.isArray(e)?e.map(t=>String(t)):[],ia=e=>{let t=new Set(Pg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Pg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((p,c)=>p||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let p of e.handlers)if(p)try{let c=()=>{e.emit("action:resubmit",d)},u=p(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var ox=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},rx=e=>e.map(t=>({...t,streaming:!1})),sx=e=>e.map(t=>({...t,status:"complete"})),Zi=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?ox(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?rx(n.messages):void 0,artifacts:n.artifacts?sx(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Qr=require("partial-json");function ax(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function ix(e,t){if(!ax(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 el(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Qr.parse)(n,Qr.STR|Qr.OBJ),s=ix(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Lg(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function tl(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Mn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Rg(){let e=el();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ig(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 la(e){let t=Ig(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 nl(e){let t=Ig(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var lx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ol(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:p=lx}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,f.appendChild(y);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let q=1;q<=5;q++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${q} star${q>1?"s":""}: ${p[q-1]}`),w.title=p[q-1],w.dataset.rating=String(q),w.innerHTML=`
|
|
41
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Pt(s),d=n.querySelector("[data-role='launcher-title']");if(d){let A=a.title??"Chat Assistant";d.textContent=A,d.setAttribute("title",A)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let A=a.subtitle??"Here to help you get answers fast";p.textContent=A,p.setAttribute("title",A)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let A=a.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let k=parseFloat(A)||24,F=re(a.agentIconName,k*.6,"var(--persona-text-inverse, #ffffff)",2);F?(u.appendChild(F),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let v=n.querySelector("[data-role='launcher-image']");if(v){let A=a.agentIconSize??"40px";v.style.height=A,v.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(v.src=a.iconUrl,v.style.display="block"):v.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=a.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let k=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,k=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let F=parseFloat(A)||24,q=Math.max(F-k,8),S=re(a.callToActionIconName,q,"currentColor",2);S?f.appendChild(S):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&Pn[a.position]?Pn[a.position]:Pn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="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?E:`${C} ${b}`,i||(n.style.zIndex=String(a.zIndex??Kt));let L="1px solid var(--persona-border, #e5e7eb)",W="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:W,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var ff=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=uf(e),s=gf(e,t),a={wrapper:n,panel:o,pillRoot:r},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:p,replaceHeader:v=>(d.element.replaceWith(v.header),d.element=v.header,d.iconHolder=v.iconHolder,d.headerTitle=v.headerTitle,d.headerSubtitle=v.headerSubtitle,d.closeButton=v.closeButton,d.closeButtonWrapper=v.closeButtonWrapper,d.clearChatButton=v.clearChatButton,d.clearChatButtonWrapper=v.clearChatButtonWrapper,v),replaceComposer:v=>{p.footer.replaceWith(v),p.footer=v}}},zc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Uc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Uc(e,n);return{instance:r,element:r.element}};var hv=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}},yv=(e,t)=>{if(!e)return null;let n=hv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},bv=(e,t)=>{let n=h("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},vv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},qc=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(":"))},Vc=320,bf=320,xv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Cv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),wv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Sv=e=>{if(!e||e.length===0)return null;let t=Ie("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ie("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=h("span","persona-mention-chip-icon"),s=re(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ie("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Tv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Vs(o.ref,{readonly:!0,render:t}))}return n},mf="\uE000",hf="\uE001",Mv=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=v=>`${mf}${r}:${v}${hf}`,a=t.map((v,f)=>v.kind==="text"?v.text:s(f)).join(""),i=n(a);if(!t.every((v,f)=>v.kind==="text"||i.includes(s(f)))){e.replaceChildren(Tv(t,o));return}e.innerHTML=i;let p=new RegExp(`${mf}${r}:(\\d+)${hf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let v=c.nextNode();v;v=c.nextNode())u.push(v);for(let v of u){let f=v;for(let b=p.exec(f.data);b;b=p.exec(f.data)){let C=t[Number(b[1])],E=f.splitText(b.index);E.data=E.data.slice(b[0].length),C?.kind==="mention"&&E.parentNode?.insertBefore(Vs(C.ref,{readonly:!0,render:o}),E),f=E}}},Ev=(e,t,n)=>{if(e.length===0)return null;try{let o=h("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,d)=>{let p=h("img");p.alt=i.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${Vc}px`,p.style.maxHeight=`${bf}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,p.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{c=!0}),vv(i.image)?(p.src=i.image,o.appendChild(p)):(c=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},kv=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!qc(o.audio))return;let r=h("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Pv=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!qc(o.video))return;let r=h("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vc}px`,r.style.maxHeight=`${bf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Lv=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!qc(o.data))return;let r=h("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},pr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Kc=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:pr};if(t){let r=t(o);if(r!==null)return r}return pr()},Rv=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=h("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},yf=(e,t,n="div")=>{let o=h(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Gc=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","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-container","persona-text-persona-text","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-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Jc=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let b=h("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}let i=t.visibility??"hover",d=t.align??"right",p=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[p],v=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id);let f=(b,C,E)=>{let L=it({icon:b,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",E),L};return o&&v.appendChild(f("copy","Copy message","copy")),a&&v.appendChild(f("volume-2","Read aloud","read-aloud")),r&&v.appendChild(f("thumbs-up","Upvote","upvote")),s&&v.appendChild(f("thumbs-down","Downvote","downvote")),v},Yr=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",d=a.avatar,p=a.timestamp,c=d?.show??!1,u=p?.show??!1,v=d?.position??"left",f=p?.position??"below",b=Gc(e.role,i),C=h("div",b.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=xv(e),L=e.content?.trim()??"",A=E.length>0&&L===gi,k=Ni(s?.widgetConfig?.features?.streamAnimation),F=s?.widgetConfig?.features?.streamAnimation?.plugins,q=e.role==="assistant"&&k.type!=="none"?Gr(k.type,F):null,S=e.role==="assistant"&&q?.isAnimating?.(e)===!0,V=e.role==="assistant"&&q!==null&&(!!e.streaming||S);V&&q?.bubbleClass&&C.classList.add(q.bubbleClass);let G=document.createElement("div");G.classList.add("persona-message-content"),e.streaming&&G.classList.add("persona-content-streaming"),V&&q&&(q.containerClass&&G.classList.add(q.containerClass),G.style.setProperty("--persona-stream-step",`${k.speed}ms`),G.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let oe=V?Fi(e.content??"",k.buffer,q,e,!!e.streaming):e.content??"",N=()=>{let Q=t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent});return V&&q?.wrap==="char"?na(Q,"char",e.id,{skipTags:q.skipTags}):V&&q?.wrap==="word"?na(Q,"word",e.id,{skipTags:q.skipTags}):Q},U=null;if(A?(U=document.createElement("div"),U.innerHTML=N(),U.style.display="none",G.appendChild(U)):e.contentSegments?.length?Mv(G,e.contentSegments,Q=>t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):G.innerHTML=N(),V&&q?.useCaret&&!A&&L){let Q=_i(),me=G.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=me[me.length-1];if(xe?.parentNode)xe.parentNode.insertBefore(Q,xe.nextSibling);else{let ye=G.lastElementChild;ye?ye.appendChild(Q):G.appendChild(Q)}}if(u&&f==="inline"&&e.createdAt){let Q=yf(e,p,"span");Q.classList.add("persona-timestamp-inline");let me=G.lastElementChild;me?me.appendChild(Q):G.appendChild(Q)}if(E.length>0){let Q=Ev(E,!A&&!!L,()=>{A&&U&&(U.style.display="")});Q?C.appendChild(Q):A&&U&&(U.style.display="")}let Z=Cv(e);if(Z.length>0){let Q=kv(Z);Q&&C.appendChild(Q)}let he=wv(e);if(he.length>0){let Q=Pv(he);Q&&C.appendChild(Q)}let ve=Av(e);if(ve.length>0){let Q=Lv(ve);Q&&C.appendChild(Q)}let ue=e.contentSegments?.length?null:Sv(e.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(G),u&&f==="below"&&e.createdAt){let Q=yf(e,p);Q.classList.add("persona-mt-1"),C.appendChild(Q)}let ne=e.role==="assistant"?yv(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(oe&&oe.trim()),me=k.placeholder==="skeleton",xe=me&&k.buffer==="line"&&Q;if(Q)xe&&C.appendChild(oa());else if(me)C.appendChild(oa());else{let ye=Kc("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&C.appendChild(ye)}}if(ne&&e.stopReason&&!e.streaming&&(L||(G.style.display="none"),C.appendChild(bv(e.stopReason,ne))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Q=Jc(e,o,r);C.appendChild(Q)}if(!c||e.role==="system")return C;let te=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=Rv(d,e.role);return v==="right"||v==="left"&&e.role==="user"?te.append(C,de):te.append(de,C),te},vf=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Yr(e,t,n,o,r,s)};var Qr=new Set,Iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Wv=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
42
|
+
`):""},xf=(e,t)=>{let n=Qr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let p=re(n?"chevron-up":"chevron-down",16,"currentColor",2);p?i.appendChild(p):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Xc=(e,t)=>{let n=e.reasoning,o=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Qr.has(e.id),i=n.status!=="complete",d=Wv(e,r.previewMaxLines??3),p=h("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",s&&(p.setAttribute("aria-expanded",a?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","reasoning");let c=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),v="Thinking...",f=t?.reasoning??{},b=String(n.startedAt??Date.now()),C=()=>{let he=h("span","");return he.setAttribute("data-tool-elapsed",b),he.textContent=ai(n),he},E=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:v,previewText:d,isActive:i,config:t??{},elapsed:ai(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(u.textContent=E,c.appendChild(u)):E instanceof HTMLElement?c.appendChild(E):(u.textContent=v,c.appendChild(u));let L=h("span","persona-text-xs persona-text-persona-primary");L.textContent=_u(n),c.appendChild(L);let W=r.loadingAnimation??"none",A=f.activeTextTemplate,k=f.completeTextTemplate,F=i?A:k,q=E instanceof HTMLElement,S=(he,ve)=>{u.textContent="";let ue=ii(he,""),ne=0;for(let fe of ue){let te=fe.styles.length>0?(()=>{let de=h("span",fe.styles.map(Q=>`persona-tool-text-${Q}`).join(" "));return u.appendChild(de),de})():u;if(fe.isDuration&&i)te.appendChild(C());else{let de=fe.isDuration?ai(n):fe.text;ve?ne=Wo(te,de,ne):te.appendChild(document.createTextNode(de))}}};if(!q&&F)if(L.style.display="none",u.style.display="",i&&W!=="none"){let he=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),W==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),S(F,!1)):(u.classList.add(`persona-tool-loading-${W}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),W==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),S(F,!0))}else S(F,!1);else if(!q&&i&&W!=="none"){u.style.display="";let he=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),W==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${W}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),W==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let ve=u.textContent||v;u.textContent="",Wo(u,ve,0)}n.status==="complete"&&(u.style.display="none")}else q||(n.status==="complete"?u.style.display="none":u.style.display="");let V=null;if(s){V=h("div","persona-flex persona-items-center");let ve=re(a?"chevron-up":"chevron-down",16,"currentColor",2);ve?V.appendChild(ve):V.textContent=a?"Hide":"Show";let ue=h("div","persona-flex persona-items-center persona-ml-auto");ue.append(V),p.append(c,ue)}else p.append(c);let G=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(G.setAttribute("data-persona-collapsed-preview","reasoning"),G.style.display="none",G.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let he=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:i,config:t??{}});Iv(G,he)||(G.textContent=d),G.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(p,G),o;let oe=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");oe.style.display=a?"":"none";let N=n.chunks.join(""),U=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return U.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),oe.appendChild(U),(()=>{if(p.setAttribute("aria-expanded",a?"true":"false"),V){V.innerHTML="";let ve=re(a?"chevron-up":"chevron-down",16,"currentColor",2);ve?V.appendChild(ve):V.textContent=a?"Hide":"Show"}oe.style.display=a?"":"none",G.style.display=a?"none":G.textContent||G.childNodes.length?"":"none"})(),o.append(p,G,oe),o};var Zr=new Set,Hv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Bv=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
|
|
43
|
+
`);let r=Mo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
44
|
+
`):""},Yc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Dv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Bv(e,o?.previewMaxLines??3),a=n?$u(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=t?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),i&&d.activeTextTemplate?p=fc(n,d.activeTextTemplate,p):!i&&d.completeTextTemplate&&(p=fc(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:i}},Cf=(e,t,n)=>{let o=Zr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let p=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(p){p.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=re(o?"chevron-up":"chevron-down",16,c,2);u?p.appendChild(u):p.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Qc=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&Zr.has(e.id),{summary:d,previewText:p,isActive:c}=Dv(e,t),u=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let v=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),C=()=>{let N=h("span","");return N.setAttribute("data-tool-elapsed",b),N.textContent=$s(n),N},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:$s(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(f.textContent=E,v.appendChild(f)):E instanceof HTMLElement?v.appendChild(E):(f.textContent=d,v.appendChild(f));let L=s.loadingAnimation??"none",W=o.activeTextTemplate,A=o.completeTextTemplate,k=c?W:A,F=E instanceof HTMLElement,q=(N,U)=>{f.textContent="";let Z=n.name?.trim()||"tool",he=ii(N,Z),ve=0;for(let ue of he){let ne=ue.styles.length>0?(()=>{let fe=h("span",ue.styles.map(te=>`persona-tool-text-${te}`).join(" "));return f.appendChild(fe),fe})():f;if(ue.isDuration&&c)ne.appendChild(C());else{let fe=ue.isDuration?$s(n):ue.text;U?ve=Wo(ne,fe,ve):ne.appendChild(document.createTextNode(fe))}}};if(!F)if(c&&L!=="none"){let N=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${N}ms`),k&&q(k,!1);else if(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${N}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),k)q(k,!0);else{let U=f.textContent||d;f.textContent="",Wo(f,U,0)}}else k&&q(k,!1);let S=null;if(a){S=h("div","persona-flex persona-items-center");let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=re(i?"chevron-up":"chevron-down",16,N,2);U?S.appendChild(U):S.textContent=i?"Hide":"Show";let Z=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Z.append(S),u.append(v,Z)}else u.append(v);let V=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","tool"),V.style.display="none",V.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&p){let N=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:c,config:t??{}});Hv(V,N)||(V.textContent=p),V.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,V),r;let G=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=i?"":"none",o.contentBackgroundColor&&(G.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(G.style.color=o.contentTextColor),o.contentPaddingX&&(G.style.paddingLeft=o.contentPaddingX,G.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(G.style.paddingTop=o.contentPaddingY,G.style.paddingBottom=o.contentPaddingY),n.name){let N=h("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?N.style.color=o.contentTextColor:o.headerTextColor&&(N.style.color=o.headerTextColor),N.textContent=n.name,G.appendChild(N)}if(n.args!==void 0){let N=h("div","persona-space-y-1"),U=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let Z=h("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");Z.style.fontSize="0.75rem",Z.style.lineHeight="1rem",Yc(Z,o),Z.textContent=Mo(n.args),N.append(U,Z),G.appendChild(N)}if(n.chunks&&n.chunks.length){let N=h("div","persona-space-y-1"),U=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let Z=h("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");Z.style.fontSize="0.75rem",Z.style.lineHeight="1rem",Yc(Z,o),Z.textContent=n.chunks.join(""),N.append(U,Z),G.appendChild(N)}if(n.status==="complete"&&n.result!==void 0){let N=h("div","persona-space-y-1"),U=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let Z=h("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");Z.style.fontSize="0.75rem",Z.style.lineHeight="1rem",Yc(Z,o),Z.textContent=Mo(n.result),N.append(U,Z),G.appendChild(N)}if(n.status==="complete"&&typeof n.duration=="number"){let N=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(N.style.color=o.contentTextColor),N.textContent=`Duration: ${n.duration}ms`,G.appendChild(N)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),S){S.innerHTML="";let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=re(i?"chevron-up":"chevron-down",16,N,2);U?S.appendChild(U):S.textContent=i?"Hide":"Show"}G.style.display=i?"":"none",V.style.display=i?"none":V.textContent||V.childNodes.length?"":"none"})(),r.append(u,V,G),r};var ur=new Map,Zi=e=>{let n=(e.startsWith(Mn)?e.slice(Mn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},wf=e=>e?.approval!==!1?e?.approval:void 0,Af=(e,t)=>{let n=wf(t)?.detailsDisplay??"collapsed";return ur.get(e)??n==="expanded"},Sf=(e,t,n)=>{let o=wf(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=re(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Tf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Af(e,n);Sf(o,s,n),r.style.display=s?"":"none"};var el=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=h("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("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",p=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=re(d,20,p,2);c&&i.appendChild(c);let u=h("div","persona-flex-1 persona-min-w-0"),v=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",v.appendChild(f),!r){let S=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");S.setAttribute("data-approval-status",n.status),n.status==="approved"?(S.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",S.style.color="var(--persona-palette-colors-success-700, #15803d)",S.textContent="Approved"):n.status==="denied"?(S.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",S.style.color="var(--persona-palette-colors-error-700, #b91c1c)",S.textContent="Denied"):n.status==="timeout"&&(S.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",S.style.color="var(--persona-palette-colors-warning-700, #b45309)",S.textContent="Timeout"),v.appendChild(S)}u.appendChild(v);let C=n.toolType==="webmcp"||n.toolName.startsWith(Mn)?Bs(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,W=E||(L?n.description:`The assistant wants to use \u201C${C??Zi(n.toolName)}\u201D.`),A=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=W,u.appendChild(A),n.reason){let S=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");S.setAttribute("data-approval-reason","true"),o?.reasonColor?S.style.color=o.reasonColor:o?.descriptionColor&&(S.style.color=o.descriptionColor);let V=h("span","persona-font-medium");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,S.appendChild(V),S.appendChild(document.createTextNode(n.reason)),u.appendChild(S)}let k=o?.detailsDisplay??"collapsed",F=!!n.description&&!L,q=F||!!n.parameters;if(k!=="hidden"&&q){let S=Af(e.id,t),V=h("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");V.type="button",V.setAttribute("data-expand-header","true"),V.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(V.style.color=o.descriptionColor);let G=h("span");G.setAttribute("data-approval-details-label","true");let oe=h("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),V.append(G,oe),Sf(V,S,t),u.appendChild(V);let N=h("div");if(N.setAttribute("data-approval-details","true"),N.style.display=S?"":"none",F){let U=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,N.appendChild(U)}if(n.parameters){let U=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=Mo(n.parameters),N.appendChild(U)}u.appendChild(N)}if(r){let S=h("div","persona-flex persona-gap-2 persona-mt-2");S.setAttribute("data-approval-buttons","true");let V=h("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");V.type="button",V.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",V.style.color=o?.approveButtonTextColor??"#ffffff",V.setAttribute("data-approval-action","approve");let G=re("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);G&&(G.style.marginRight="4px",V.appendChild(G));let oe=document.createTextNode(o?.approveLabel??"Approve");V.appendChild(oe);let N=h("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");N.type="button",N.style.backgroundColor=o?.denyButtonColor??"transparent",N.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",N.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,N.setAttribute("data-approval-action","deny");let U=re("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",N.appendChild(U));let Z=document.createTextNode(o?.denyLabel??"Deny");N.appendChild(Z),S.append(V,N),u.appendChild(S)}return a.append(i,u),s.appendChild(a),s};function Ov(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Mf(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:d=2147483e3,onOpen:p,onDismiss:c}=e,u=e.container??Ov(t),v=!1,f=null,b=()=>{if(!v)return;let L=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${L.width}px`),a&&(n.style.maxWidth=`${L.width}px`);let W=n.getBoundingClientRect(),A=i?.()??null,k=A!=null?L.top+A:L.top,F=o==="top-start"||o==="top-end"?k-r-W.height:L.bottom+r,S=o==="bottom-end"||o==="top-end"?L.right-W.width:L.left,V=a?.()??null;if(V!=null){let G=Math.max(L.left,L.right-W.width);S=Math.min(Math.max(L.left+V,L.left),G)}n.style.top=`${F}px`,n.style.left=`${S}px`},C=()=>{v&&(v=!1,f&&(f(),f=null),n.remove())},E=()=>{if(v)return;v=!0,d!=null&&(n.style.zIndex=String(d)),u.appendChild(n),b();let L=(t.ownerDocument??document).defaultView??window,W=t.ownerDocument??document,A=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}b()},k=q=>{let S=typeof q.composedPath=="function"?q.composedPath():[];S.includes(n)||S.includes(t)||(C(),c?.("outside"))},F=L.setTimeout(()=>{W.addEventListener("pointerdown",k,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(F),W.removeEventListener("pointerdown",k,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},p?.()};return{get isOpen(){return v},open:E,close:C,toggle:()=>v?C():E(),reposition:b,destroy:C}}function Ef(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Nv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),kf=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},gr=(e,t)=>{kf(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Fv=e=>e?.approval!==!1?e?.approval:void 0,_v=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return ur.get(e)??n==="expanded"},Zc=e=>{let t=h("span","persona-approval-kbd");return t.textContent=e,t},$v=(e,t)=>{let n=h("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Mn)?Bs(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Zi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let p=document.createElement("strong");p.textContent=i,n.appendChild(p)}return n},jv=e=>{let t=h("div","persona-approval-resolved"),n=re("ban",15,"currentColor",2);n&&t.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=e.toolName?Zi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Uv=(e,t,n,o,r,s,a)=>{let i=h("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",p=!!n.description&&d!=="hidden",c=n.parameters!=null&&d!=="hidden",u=p||c,v=u&&_v(t.id,o),f=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",C=h("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",v?"true":"false"),C.setAttribute("aria-label",v?b:f)):C.setAttribute("data-static","true");let E=h("span","persona-approval-logo"),L=re("shield-check",16,"currentColor",2);L&&E.appendChild(L),C.appendChild(E);let W=$v(n,o);if(u){let V=h("span","persona-approval-toggle");V.setAttribute("aria-hidden","true");let G=re("chevron-down",14,"currentColor",2);G&&V.appendChild(G),W.append(" "),W.appendChild(V)}C.appendChild(W),i.appendChild(C);let A=h("div","persona-approval-body");if(u){let V=h("div","persona-approval-details");if(V.setAttribute("data-role","params"),V.hidden=!v,p){let G=h("p","persona-approval-desc");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,V.appendChild(G)}if(c){let G=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(G.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.textContent=Mo(n.parameters),V.appendChild(G)}A.appendChild(V)}if(n.reason){let V=h("p","persona-approval-reason");o?.reasonColor?V.style.color=o.reasonColor:o?.descriptionColor&&(V.style.color=o.descriptionColor);let G=h("span","persona-approval-reason-label");G.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,V.append(G,document.createTextNode(n.reason)),A.appendChild(V)}let k=h("div","persona-approval-actions"),F=null,q=V=>{o?.approveButtonColor&&(V.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(V.style.color=o.approveButtonTextColor)},S=h("button","persona-approval-deny");if(S.type="button",S.setAttribute("data-action","deny"),o?.denyButtonColor&&(S.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(S.style.color=o.denyButtonTextColor),S.append(o?.denyLabel??"Deny"),a){let V=h("div","persona-approval-split"),G=h("button","persona-approval-primary");G.type="button",G.setAttribute("data-action","always"),q(G),G.append(o?.approveLabel??"Always allow",Zc("\u23CE"));let oe=h("button","persona-approval-caret");oe.type="button",oe.setAttribute("data-action","toggle-menu"),oe.setAttribute("aria-label","More options"),q(oe);let N=re("chevron-down",15,"currentColor",2);N&&oe.appendChild(N),V.append(G,oe),k.append(V,S),S.append(Zc("Esc"));let U=h("div","persona-approval-menu"),Z=h("button","persona-approval-menu-item");Z.type="button",Z.append("Allow once",Zc("\u2318\u23CE")),U.appendChild(Z),F=Mf({anchor:V,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,F),Z.addEventListener("click",()=>{gr(e,t.id),r()})}else{let V=h("button","persona-approval-primary persona-approval-primary--solo");V.type="button",V.setAttribute("data-action","allow"),q(V),V.append(o?.approveLabel??"Allow"),k.append(V,S)}return A.appendChild(k),i.appendChild(A),i.addEventListener("click",V=>{let G=V.target instanceof Element?V.target.closest("[data-action]"):null;if(!G)return;let oe=G.getAttribute("data-action");if(oe==="toggle-params"){let N=i.querySelector('[data-role="params"]');if(N){let U=N.hidden;N.hidden=!U,C.setAttribute("aria-expanded",U?"true":"false"),C.setAttribute("aria-label",U?b:f),ur.set(t.id,U)}return}if(oe==="toggle-menu"){F?.toggle();return}if(oe==="always"){gr(e,t.id),r({remember:!0});return}if(oe==="allow"){gr(e,t.id),r();return}if(oe==="deny"){gr(e,t.id),s();return}}),i},Pf=()=>{let e=Nv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let d=Fv(a);if(i.status!=="pending"){if(gr(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return jv(i)}kf(e,o.id);let p=d?.enableAlwaysAllow===!0,c=Uv(e,o,i,d,r,s,p);if(p){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=v=>{Ef(v)||o.id===e.latestPendingApprovalId&&(v.key!=="Escape"&&v.key!=="Enter"||(v.preventDefault(),v.stopImmediatePropagation(),gr(e,o.id),v.key==="Escape"?s():v.metaKey||v.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])gr(e,o);e.latestPendingApprovalId=null}}};var aa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ia=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var zv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),qv=new Set(["step_start","execution_start"]),Vv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Kv=new Set(["step_complete","agent_turn_complete"]),Gv=new Set(["flow_complete","agent_complete"]),Lf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),If=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fr=(e,t)=>{let n=e[t];return If(n)?n:void 0};function ed(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function tl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Jv(e,t){return typeof t.type=="string"?t.type:e}function Xv(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 Yv(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 Rf(e){let t=fr(e,"result"),n=[fr(e,"tokens"),fr(e,"totalTokens"),t?fr(t,"tokens"):void 0,fr(e,"usage"),t?fr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=pn(o.output)??pn(o.outputTokens)??pn(o.completionTokens);if(r!==void 0)return r}return pn(e.outputTokens)??pn(e.completionTokens)??(t?pn(t.outputTokens)??pn(t.completionTokens):void 0)}function Qv(e){let t=fr(e,"result");return pn(e.executionTime)??pn(e.executionTimeMs)??pn(e.execution_time)??pn(e.duration)??(t?pn(t.executionTime)??pn(t.executionTimeMs):void 0)}function Zv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var la=class{constructor(t=Zv){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:tl(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!If(n)){Lf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Jv(t,n),r=this.now();if(zv.has(o)){this.startRun(r);return}if(qv.has(o)){this.run||this.startRun(r);return}if(Vv.has(o)){if(!Yv(o,n))return;let s=Xv(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+ed(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:tl(i,d),outputTokens:i,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Kv.has(o)){if(!this.run)return;let s=this.run,a=Rf(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,d=s.exactOutputTokens+ed(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:tl(d,p),outputTokens:d,durationMs:p,source:i?"usage":"estimate"};return}if(Gv.has(o)){if(!this.run)return;let s=this.run,a=Rf(n),i=a??s.exactOutputTokens+ed(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:tl(i,p),outputTokens:i,durationMs:p,source:d},this.run=null;return}if(Lf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Qv(n)??o-t.startedAt}};function es(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var ex={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},tx={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},nx=["flowName","stepName","reasoningText","text","name","tool","toolName"],ox=100;function rx(e,t){let n={...ex,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return tx}function sx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ax(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function ix(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function lx(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function cx(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function dx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function px(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 ux(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=h("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=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function td(e,t,n,o,r,s,a,i){let d=r.has(e.id),p=h("div","persona-border-b persona-border-persona-divider persona-text-xs");es(p,o.classNames?.eventRow);let c=a.find(v=>v.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let v=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(v)return p.appendChild(v),p}return p.appendChild(u()),p;function u(){let v=h("div",""),f=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let b=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=re(d?"chevron-down":"chevron-right","14px","currentColor",2);C&&b.appendChild(C);let E=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";E.textContent=L==="relative"?sx(e.timestamp,n):ax(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let A=rx(e.type,o.badgeColors),k=h("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");k.style.backgroundColor=A.bg,k.style.color=A.text,k.style.borderColor=A.text+"50",k.textContent=e.type;let F=o.descriptionFields??nx,q=ix(e.payload,F),S=null;q&&(S=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),S.textContent=q);let V=h("div","persona-flex-1 persona-min-w-0"),G=h("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"),oe=re("clipboard","12px","currentColor",1.5);return oe&&G.appendChild(oe),G.addEventListener("click",async N=>{N.stopPropagation(),await lx(cx(e)),G.innerHTML="";let U=re("check","12px","currentColor",1.5);U&&G.appendChild(U),setTimeout(()=>{G.innerHTML="";let Z=re("clipboard","12px","currentColor",1.5);Z&&G.appendChild(Z)},1500)}),f.appendChild(b),f.appendChild(E),W&&f.appendChild(W),f.appendChild(k),S&&f.appendChild(S),f.appendChild(V),f.appendChild(G),v.appendChild(f),d&&v.appendChild(ux(e,a,i)),v}}function Wf(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,d=i?.enabled!==!1,p=i?.iconName??"arrow-down",c=i?.label??"",u=r?.features?.eventStream??{},v=s.find(b=>b.renderEventStreamView);if(v?.renderEventStreamView&&r){let b=v.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return f();function f(){let b=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");es(C,b?.panel);let E=[],L="",W="",A=null,k=[],F={},q=0,S=Bi(),V=0,G=0,oe=!1,N=null,U=!1,Z=0,he=new Set,ve=new Map,ue="",ne="",fe=null,te,de,Q,me,xe=null,ye=null,Ae=null;function Ee(){let H=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),X=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(es(X,b?.headerBar),a){ye=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",xe=h("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"),xe.textContent="-- tok/s",Ae=h("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"),Ae.style.display="none",Ae.style.pointerEvents="none";let Ne=ye,Ot=Ae,At=()=>{if(!Ot.textContent)return;let ba=Ne.getBoundingClientRect(),so=H.getBoundingClientRect();Ot.style.left=`${ba.left-so.left}px`,Ot.style.top=`${ba.bottom-so.top+4}px`,Ot.style.display="block"},Jt=()=>{Ot.style.display="none"};ye.addEventListener("mouseenter",At),ye.addEventListener("mouseleave",Jt),ye.appendChild(xe)}let ie=h("div","persona-flex-1");te=h("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 Pe=h("option","");Pe.value="",Pe.textContent="All events (0)",te.appendChild(Pe),de=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let rt=re("clipboard-copy","12px","currentColor",1.5);rt&&de.appendChild(rt);let nt=h("span","persona-event-copy-all persona-text-xs");nt.textContent="Copy All",de.appendChild(nt),ye&&X.appendChild(ye),X.appendChild(ie),X.appendChild(te),X.appendChild(de);let ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");es(ze,b?.searchBar);let Qe=re("search","14px","var(--persona-muted, #9ca3af)",1.5),K=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Qe&&K.appendChild(Qe),Q=h("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"),es(Q,b?.searchInput),Q.type="text",Q.placeholder="Search event payloads...",me=h("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"),me.type="button",me.style.display="none";let qe=re("x","12px","currentColor",2);return qe&&me.appendChild(qe),ze.appendChild(K),ze.appendChild(Q),ze.appendChild(me),H.appendChild(X),H.appendChild(ze),Ae&&H.appendChild(Ae),H}let Se,Te=s.find(H=>H.renderEventStreamToolbar);Te?.renderEventStreamToolbar&&r?Se=Te.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ee(),eventCount:t.getSize(),filteredCount:0,onFilterChange:X=>{L=X,Ye(),le()},onSearchChange:X=>{W=X,Ye(),le()}})??Ee():Se=Ee();let Fe=h("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");Fe.style.display="none";function Ue(){if(!a||!xe||!ye)return;let H=a(),X=dx(H);xe.textContent=X;let ie=px(H);Ae&&(Ae.textContent=ie,ie||(Ae.style.display="none")),ye.setAttribute("aria-label",ie?`Throughput: ${X}, ${ie}`:`Throughput: ${X}`)}let ke=h("div","persona-flex-1 persona-min-h-0 persona-relative"),ce=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ce.style.height="100%";let We=h("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");es(We,b?.scrollIndicator),We.style.display="none",We.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let ot=re(p,"14px","currentColor",2);ot&&We.appendChild(ot);let bt=h("span","");bt.textContent=c,We.appendChild(bt);let Lt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Lt.style.display="none",ke.appendChild(ce),ke.appendChild(Lt),ke.appendChild(We),C.setAttribute("tabindex","0"),C.appendChild(Se),C.appendChild(Fe),C.appendChild(ke);function Tt(){let H=t.getAll(),X={};for(let ze of H)X[ze.type]=(X[ze.type]||0)+1;let ie=Object.keys(X).sort(),Pe=ie.length!==k.length||!ie.every((ze,Qe)=>ze===k[Qe]),we=!Pe&&ie.some(ze=>X[ze]!==F[ze]),rt=H.length!==Object.values(F).reduce((ze,Qe)=>ze+Qe,0);if(!Pe&&!we&&!rt||(k=ie,F=X,!te))return;let nt=te.value;if(te.options[0].textContent=`All events (${H.length})`,Pe){for(;te.options.length>1;)te.remove(1);for(let ze of ie){let Qe=h("option","");Qe.value=ze,Qe.textContent=`${ze} (${X[ze]||0})`,te.appendChild(Qe)}nt&&ie.includes(nt)?te.value=nt:nt&&(te.value="",L="")}else for(let ze=1;ze<te.options.length;ze++){let Qe=te.options[ze];Qe.textContent=`${Qe.value} (${X[Qe.value]||0})`}}function Oe(){let H=t.getAll();if(L&&(H=H.filter(X=>X.type===L)),W){let X=W.toLowerCase();H=H.filter(ie=>ie.type.toLowerCase().includes(X)||ie.payload.toLowerCase().includes(X))}return H}function ge(){return L!==""||W!==""}function Ye(){q=0,V=0,S.resume(),We.style.display="none"}function Be(H){he.has(H)?he.delete(H):he.add(H),fe=H;let X=ce.scrollTop,ie=S.isFollowing();U=!0,S.pause(),le(),ce.scrollTop=X,ie&&S.resume(),U=!1}function be(){return Do(ce,50)}function le(){G=Date.now(),oe=!1,Ue(),Tt();let H=t.getEvictedCount();H>0?(Fe.textContent=`${H.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",E=Oe();let X=E.length,ie=t.getSize()>0;X===0&&ie&&ge()?(Lt.textContent=W?`No events matching '${W}'`:"No events matching filter",Lt.style.display="",ce.style.display="none"):(Lt.style.display="none",ce.style.display=""),de&&(de.title=ge()?`Copy Filtered (${X})`:"Copy All"),d&&!S.isFollowing()&&X>q&&(V+=X-q,bt.textContent=c?`${c}${V>0?` (${V})`:""}`:"",We.style.display=""),q=X;let Pe=t.getAll(),we=Pe.length>0?Pe[0].timestamp:0,rt=new Set(E.map(Qe=>Qe.id));for(let Qe of he)rt.has(Qe)||he.delete(Qe);let nt=L!==ue||W!==ne,ze=ve.size===0&&E.length>0;if(nt||ze||E.length===0){ce.innerHTML="",ve.clear();let Qe=document.createDocumentFragment();for(let K=0;K<E.length;K++){let qe=td(E[K],K,we,u,he,Be,s,r);ve.set(E[K].id,qe),Qe.appendChild(qe)}ce.appendChild(Qe),ue=L,ne=W,fe=null}else{if(fe!==null){let K=ve.get(fe);if(K&&K.parentNode===ce){let qe=E.findIndex(Ne=>Ne.id===fe);if(qe>=0){let Ne=td(E[qe],qe,we,u,he,Be,s,r);ce.insertBefore(Ne,K),K.remove(),ve.set(fe,Ne)}}fe=null}let Qe=new Set(E.map(K=>K.id));for(let[K,qe]of ve)Qe.has(K)||(qe.remove(),ve.delete(K));for(let K=0;K<E.length;K++){let qe=E[K];if(!ve.has(qe.id)){let Ne=td(qe,K,we,u,he,Be,s,r);ve.set(qe.id,Ne),ce.appendChild(Ne)}}}S.isFollowing()&&(ce.scrollTop=ce.scrollHeight)}function He(){if(Date.now()-G>=ox){N!==null&&(cancelAnimationFrame(N),N=null),le();return}oe||(oe=!0,N=requestAnimationFrame(()=>{N=null,le()}))}let Gt=(H,X)=>{if(!de)return;de.innerHTML="";let ie=re(H,"12px","currentColor",1.5);ie&&de.appendChild(ie);let Pe=h("span","persona-text-xs");Pe.textContent="Copy All",de.appendChild(Pe),setTimeout(()=>{de.innerHTML="";let we=re("clipboard-copy","12px","currentColor",1.5);we&&de.appendChild(we);let rt=h("span","persona-text-xs");rt.textContent="Copy All",de.appendChild(rt),de.disabled=!1},X)},ft=async()=>{if(de){de.disabled=!0;try{let H;ge()?H=E:n?(H=await n(),H.length===0&&(H=t.getAll())):H=t.getAll();let X=H.map(ie=>{try{return JSON.parse(ie.payload)}catch{return ie.payload}});await navigator.clipboard.writeText(JSON.stringify(X,null,2)),Gt("check",1500)}catch{Gt("x",1500)}}},vt=()=>{te&&(L=te.value,Ye(),le())},z=()=>{!Q||!me||(me.style.display=Q.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{W=Q.value,Ye(),le()},150))},w=()=>{!Q||!me||(Q.value="",W="",me.style.display="none",A&&clearTimeout(A),Ye(),le())},j=()=>{if(U)return;let H=ce.scrollTop,{action:X,nextLastScrollTop:ie}=Di({following:S.isFollowing(),currentScrollTop:H,lastScrollTop:Z,nearBottom:be(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Z=ie,X==="resume"?(S.resume(),V=0,We.style.display="none"):X==="pause"&&(S.pause(),d&&(bt.textContent=c,We.style.display=""))},y=H=>{let X=Oi({following:S.isFollowing(),deltaY:H.deltaY,nearBottom:be(),resumeWhenNearBottom:!0});X==="pause"?(S.pause(),d&&(bt.textContent=c,We.style.display="")):X==="resume"&&(S.resume(),V=0,We.style.display="none")},R=()=>{d&&(ce.scrollTop=ce.scrollHeight,S.resume(),V=0,We.style.display="none")},I=H=>{let X=H.target;if(!X||X.closest("button"))return;let ie=X.closest("[data-event-id]");if(!ie)return;let Pe=ie.getAttribute("data-event-id");Pe&&Be(Pe)},D=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),Q?.focus(),Q?.select();return}H.key==="Escape"&&(Q&&document.activeElement===Q?(w(),Q.blur(),C.focus()):o&&o())};de&&de.addEventListener("click",ft),te&&te.addEventListener("change",vt),Q&&Q.addEventListener("input",z),me&&me.addEventListener("click",w),ce.addEventListener("scroll",j),ce.addEventListener("wheel",y,{passive:!0}),ce.addEventListener("click",I),We.addEventListener("click",R),C.addEventListener("keydown",D);function O(){A&&clearTimeout(A),N!==null&&(cancelAnimationFrame(N),N=null),oe=!1,ve.clear(),de&&de.removeEventListener("click",ft),te&&te.removeEventListener("change",vt),Q&&Q.removeEventListener("input",z),me&&me.removeEventListener("click",w),ce.removeEventListener("scroll",j),ce.removeEventListener("wheel",y),ce.removeEventListener("click",I),We.removeEventListener("click",R),C.removeEventListener("keydown",D)}return{element:C,update:He,destroy:O}}}function nl(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},d=u=>{let v=u;return s.findIndex(f=>f===v||f.contains(v))},p=u=>{let v=d(u.target);if(v<0)return;let f=v;if(u.key===r)f=Math.min(v+1,s.length-1);else if(u.key===o)f=Math.max(v-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==v&&t.onSelect(f)},c=u=>{let v=d(u.target);v>=0&&i(s[v])};return e.addEventListener("keydown",p),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,v){if(s=u,u.forEach((f,b)=>{f.setAttribute("role","tab");let C=b===v;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||v<0&&b===0?0:-1}),a){let f=(v>=0?u[v]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",c)}}}function Hf(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),p=z=>({start:z===!1?!1:typeof z=="object"&&z?z.start!==!1:!0,end:z===!1?!1:typeof z=="object"&&z?z.end!==!1:!0}),{start:c,end:u}=p(n?.tabFade),v=typeof document<"u"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{v?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),U?.hide()};v&&v.addEventListener("click",()=>{f(),t.onDismiss?.()});let b=h("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");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let E=h("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=s;let L=it({icon:"x",label:a});L.addEventListener("click",()=>{f(),t.onDismiss?.()});let W="rendered",A=to({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:z=>{W=z==="source"?"source":"rendered",Gt()}}),k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),F=n?.documentToolbarShowCopyLabel===!0,q=n?.documentToolbarShowCopyChevron===!0,S=n?.documentToolbarCopyMenuItems,V=!!(q&&S&&S.length>0),G=null,oe,N=null,U=null;if(r&&(F||q)&&!V){if(oe=F?eo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):it({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),q){let z=re("chevron-down",14,"currentColor",2);z&&oe.appendChild(z)}}else r&&V?(G=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),oe=F?eo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):it({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N=it({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"}}),G.append(oe,N)):r?oe=it({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(oe=it({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&oe.classList.add("persona-hidden"));let Z=r?it({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):it({icon:"refresh-cw",label:"Refresh"}),he=r?it({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):it({icon:"x",label:a}),ve=it({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&ve.classList.add("persona-hidden");let ue=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ne=e.features?.artifacts?.toolbarActions??[],fe=()=>{let z=ke.find(R=>R.id===ce)??ke[ke.length-1],w=z?.id??null,j=z?.artifactType==="markdown"?z.markdown??"":"",y=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:j,jsonPayload:y,id:w}},te=async()=>{let z=ke.find(w=>w.id===ce)??ke[ke.length-1];try{await navigator.clipboard.writeText(Zs(z))}catch{}};if(oe.addEventListener("click",async()=>{let z=n?.onDocumentToolbarCopyMenuSelect;if(z&&V){let{markdown:w,jsonPayload:j,id:y}=fe();try{await z({actionId:"primary",artifactId:y,markdown:w,jsonPayload:j})}catch{}return}await te()}),N&&S?.length){let z=()=>b.closest("[data-persona-root]")??document.body,w=()=>{U=Ho({items:S.map(j=>({id:j.id,label:j.label})),onSelect:async j=>{let{markdown:y,jsonPayload:R,id:I}=fe(),D=n?.onDocumentToolbarCopyMenuSelect;try{D?await D({actionId:j,artifactId:I,markdown:y,jsonPayload:R}):j==="markdown"||j==="md"?await navigator.clipboard.writeText(y):j==="json"||j==="source"?await navigator.clipboard.writeText(R):await navigator.clipboard.writeText(y||R)}catch{}},anchor:G??N,position:"bottom-right",portal:z()})};b.isConnected?w():requestAnimationFrame(w),N.addEventListener("click",j=>{j.stopPropagation(),U?.toggle()})}Z.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Gt()}),he.addEventListener("click",()=>{f(),t.onDismiss?.()});let de=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),G?k.append(G,Z,he):k.append(oe,Z,he),k.insertBefore(ue,he),k.insertBefore(ve,he),C.append(A.element,de,k);else{let z=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");z.append(oe,ue,ve,L),C.appendChild(E),C.appendChild(z)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Q=h("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");d&&Q.style.setProperty("--persona-artifact-tab-fade-size",d);let me=e.features?.artifacts?.renderTabBar,xe=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=nl(Q,{onSelect:z=>t.onSelect(ke[z].id)}),Ae=z=>{let w=z.scrollWidth-z.clientWidth,j=w>1,y=Math.abs(z.scrollLeft);z.classList.toggle("persona-artifact-tab-fade-start",c&&j&&y>1),z.classList.toggle("persona-artifact-tab-fade-end",u&&j&&y<w-1)},Ee=0,Se=()=>{if(Ee)return;let z=()=>{Ee=0,Ae(Q)};Ee=typeof requestAnimationFrame=="function"?requestAnimationFrame(z):setTimeout(z,0)};Q.addEventListener("scroll",()=>Se(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ae(Q)).observe(Q);let Te=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Fe=()=>{Te.scrollLeft=0},Ue=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Fe):setTimeout(Fe,0)};if(i){for(let z of[Q,xe])z.style.paddingLeft=i,z.style.paddingRight=i;Te.style.padding=i}b.appendChild(C),b.appendChild(Q),b.appendChild(xe),b.appendChild(Te);let ke=[],ce=null,We=!1,ot=!1,bt=!0,Lt=!1,Tt=null,Oe="",ge=null,Ye=!1,Be=z=>z.artifactType==="markdown"&&!!z.file||r?W:"rendered",be=z=>{r||(z&&!Ye?(C.insertBefore(A.element,E),Ye=!0):!z&&Ye&&(A.element.remove(),Ye=!1))},le=()=>ce&&ke.find(z=>z.id===ce)||ke[ke.length-1],He=()=>{let z=Ys(le());if(!z){ue.replaceChildren();return}let w=ne.filter(j=>j.visible===void 0||j.visible(z)).map(j=>Kr(j,{documentChrome:r,onClick:()=>{let y=Ys(le());if(y)try{Promise.resolve(j.onClick(y)).catch(()=>{})}catch{}}}));ue.replaceChildren(...w)},Gt=()=>{He();let z=r&&ke.length<=1,w=!!me;if(Q.classList.toggle("persona-hidden",z||w),xe.classList.toggle("persona-hidden",z||!w),w&&me){let R=ke.map(I=>I.id).join("|")+" "+(ce??"");if(R!==Oe){Oe=R;let I=me({records:ke,selectedId:ce,onSelect:t.onSelect});xe.firstElementChild!==I&&xe.replaceChildren(I)}}else{ye.beforeRender(),Q.replaceChildren();let R=[],I=-1;for(let[D,O]of ke.entries()){let H=h("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");H.type="button";let X=O.artifactType==="markdown"?O.file:void 0,ie=X?Dn(X.path):O.title||O.id.slice(0,8),Pe=X?.path||O.title||ie;H.textContent=ie,H.title=Pe,H.setAttribute("aria-label",Pe),O.id===ce&&(H.classList.add("persona-bg-persona-container","persona-border-persona-border"),I=D),H.addEventListener("click",()=>t.onSelect(O.id)),Q.appendChild(H),R.push(H)}if(ye.render(R,I),I>=0&&ce!==Tt){Tt=ce;let D=R[I];typeof D.scrollIntoView=="function"&&D.scrollIntoView({block:"nearest",inline:"nearest"})}Ae(Q)}let j=ce&&ke.find(R=>R.id===ce)||ke[ke.length-1];if(!j){Te.replaceChildren(),ge=null,be(!1);return}let y=j.artifactType==="markdown"?j.file:void 0;if(be(!!y),r){let R=y?Io(y):j.artifactType==="markdown"?"MD":j.component??"Component",I=(j.title||"Document").trim(),D=y?Dn(y.path):I.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${D} \xB7 ${R}`}else E.textContent=y?Dn(y.path):s;ge?(ge.el.parentElement!==Te&&Te.replaceChildren(ge.el),ge.update(j)):(ge=Wi(j,{config:e,resolveViewMode:Be}),Te.replaceChildren(ge.el)),Te.classList.toggle("persona-artifact-content-flush",!!Te.querySelector(".persona-code-pre"))},ft=()=>{let z=ke.length>0;if(b.classList.toggle("persona-hidden",!z),v){let y=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;z&&y&&We?(v.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(v.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},vt=()=>{Lt=!1,Gt(),ft()};return{element:b,backdrop:v,update(z){let w=z.selectedId??z.artifacts[z.artifacts.length-1]?.id??null,j=w!==ce;ke=z.artifacts,ce=w,ke.length>0&&(We=!0),Lt=!0,bt&&vt(),j&&Fe()},setMobileOpen(z){We=z,!z&&v?(v.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ft()},setExpanded(z){z!==ot&&(ot=z,Ue());let w=re(z?"minimize":"maximize",16,"currentColor",2);w&&ve.replaceChildren(w);let j=z?"Collapse artifacts panel":"Expand artifacts panel";ve.setAttribute("aria-label",j),ve.title=j},setExpandToggleVisible(z){ve.classList.toggle("persona-hidden",!z)},setCopyButtonVisible(z){r||oe.classList.toggle("persona-hidden",!z)},setCustomActions(z){ne=z,He()},setTabFade(z){let w=p(z);w.start===c&&w.end===u||(c=w.start,u=w.end,Ae(Q))},setRenderTabBar(z){z!==me&&(me=z,Oe="",Gt())},setVisible(z){z!==bt&&(bt=z,z&&Lt&&vt())}}}function Zt(e){return e?.features?.artifacts?.enabled===!0}function Bf(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function gx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Df=["panel","seamless","detached"];function nd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Df.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function od(e){return!e||!Zt(e)?!1:nd(e)==="detached"}function ca(e,t){if(!Zt(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"),gx(e),Bf(e,t);return}let n=t.features?.artifacts?.layout,o=nd(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let d=n?.documentToolbarToggleActiveBorderColor?.trim();d?e.style.setProperty("--persona-artifact-doc-toggle-active-border",d):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Bf(e,t)}function da(e,t){for(let i of Df)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=nd(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function Of(e,t){return!t||!Zt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var fx=new Set(["__proto__","prototype","constructor"]),mx=new Set(["collapsed","card","panel","inline"]),Nf=new Set(["markdown","component"]),hx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,mr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rl=e=>!fx.has(e),rd=e=>typeof e=="string"&&mx.has(e),hr=e=>Object.keys(e).length>0;function Nn(e,t,n,o){e.push({path:t,code:n,message:o})}var yx="Ignored because this key is not part of the persisted preference schema.",ol="Ignored an unsupported value.",bx="Expected collapsed, panel, or inline.",vx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Ff={kind:"mode",message:ol},ts={kind:"string",message:"Expected a CSS length string."},oo={kind:"boolean"},xx={paneWidth:ts,paneMaxWidth:ts,paneMinWidth:ts,expandedPanelWidth:ts,resizableMinWidth:ts,resizableMaxWidth:ts,expandLauncherPanelWhenOpen:oo,resizable:oo},Cx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:oo,showReasoning:oo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ol},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ol},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ol},expandable:oo,grouped:oo}},reasoningDisplay:{kind:"object",children:{expandable:oo,activePreview:oo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Ff,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Ff,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Nf,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Nf}}},filePreview:{kind:"object",children:{enabled:oo}},layout:{kind:"object",children:xx}}}}};function _f(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Nn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Nn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Nn(o,n,"invalid_value",t.message);case"mode":return rd(e)?nn(e):Nn(o,n,"invalid_value",t.message);case"modeMap":{if(!mr(e))return Nn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,i]of Object.entries(e)){let d=r?a:xo(a);rl(a)&&(r?r.has(a):hx.test(d))?rd(i)?s[d]=nn(i):Nn(o,`${n}.${a}`,"invalid_value",bx):Nn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":vx)}return hr(s)?s:void 0}case"object":{if(t.bareMode&&rd(e))return nn(e);if(!mr(e))return Nn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=i=>n?`${n}.${i}`:i;for(let i of Object.keys(e))(!rl(i)||!r.includes(i))&&Nn(o,s(i),"unknown_key",yx);let a={};for(let i of r){let d=t.children[i],p=_f(e[i],d,s(i),o);if(d.deprecated&&e[i]!==void 0&&Nn(o,s(i),"deprecated_key",d.deprecated),p===void 0)continue;let c=d.alias??i,u=a[c];a[c]=mr(u)&&mr(p)?{...u,...p}:p}return hr(a)?a:void 0}}}function sd(e){let t=[];return{preferences:(e===null?void 0:_f(e,Cx,"",t))??{},issues:t}}function ns(e){if(Array.isArray(e))return e.map(ns);if(!mr(e))return e;let t={};for(let[n,o]of Object.entries(e))rl(n)&&o!==void 0&&(t[n]=ns(o));return t}function $f(e,t){let n=ns(e);for(let[o,r]of Object.entries(t)){if(!rl(o)||r===void 0)continue;let s=n[o];n[o]=mr(s)&&mr(r)?$f(s,r):ns(r)}return n}function wx(e){let t={},n;for(let r of e){let s=sd(r).preferences;n=jf(n,s.artifacts?.display),t=$f(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Ax(e,t){if(t===void 0)return e===void 0?void 0:ns(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...hr(r)?{byMediaType:r}:{}};return hr(s)?s:void 0}function jf(e,t){if(t===void 0)return e===void 0?void 0:ns(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Ax(n.files,t.files),a={...o?{default:o}:{},...hr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return hr(a)?a:void 0}function ad(e={},t){let n=wx(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=jf(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function pa(e){let t=e.preferences;return!t||!hr(t)?e:{...e,features:ad(e.features??{},[t])}}function Sx(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Tx(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Mx(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Ex(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function id(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Uf(e,t,n,o,r,s){let a=Sx(r,200),i=Ex(t,n,o,200);i=Math.max(a,i);let d=Tx(s);return d!==null&&(i=Math.min(i,d)),Mx(e,a,i)}var zf={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},ld=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=zf[a]??zf.init;s.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),p=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=i.title,d.appendChild(p),i.description){let b=h("p","persona-text-sm persona-text-persona-muted");b.textContent=i.description,d.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(b=>{let C=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${b.name}`;let E=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=b.label,C.appendChild(E);let L=b.type??"text",W;L==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=L),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${b.name}`,W.name=b.name,W.placeholder=b.placeholder??"",b.required&&(W.required=!0),C.appendChild(W),c.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),v=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(v),u.appendChild(f),c.appendChild(u),s.replaceChildren(d,c),c.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",E=new FormData(c),L={};E.forEach((W,A)=>{L[A]=W}),L.type=a,f.disabled=!0,v.textContent="Submitting\u2026";try{let W=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let A=await W.json();v.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(W){v.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var cd=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ua=new cd;var qf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Vf=(e,t,n)=>{if(!qf(e)||!qf(t)||kx.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Vf(e[r],t[r],s)}return o};function sl(e,t){let n=Vf(e,t,"");return Ur(n)}var Kf=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var Px=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Lx=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},ga=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Px(e),n=Lx(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},dd=e=>typeof e=="string"?e:e==null?"":String(e),yr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:dd(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=dd(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:dd(n.text)}}},Gf=e=>Array.isArray(e)?e.map(t=>String(t)):[],fa=e=>{let t=new Set(Gf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Gf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((p,c)=>p||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let p of e.handlers)if(p)try{let c=()=>{e.emit("action:resubmit",d)},u=p(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let v=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:v,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var Rx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ix=e=>e.map(t=>({...t,streaming:!1})),Wx=e=>e.map(t=>({...t,status:"complete"})),al=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Rx(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Ix(n.messages):void 0,artifacts:n.artifacts?Wx(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var os=require("partial-json");function Hx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Bx(e,t){if(!Hx(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 il(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,os.parse)(n,os.STR|os.OBJ),s=Bx(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Jf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ll(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=kn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Xf(){let e=il();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Yf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function ma(e){let t=Yf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function cl(e){let t=Yf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Dx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function dl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:p=Dx}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,v=document.createElement("div");v.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,f.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),v.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let q=1;q<=5;q++){let S=document.createElement("button");S.type="button",S.className="persona-feedback-rating-btn persona-feedback-star-btn",S.setAttribute("role","radio"),S.setAttribute("aria-checked","false"),S.setAttribute("aria-label",`${q} star${q>1?"s":""}: ${p[q-1]}`),S.title=p[q-1],S.dataset.rating=String(q),S.innerHTML=`
|
|
45
45
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
46
46
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
47
47
|
</svg>
|
|
48
|
-
`,w.addEventListener("click",()=>{u=q,L.forEach((z,V)=>{let te=V<q;z.classList.toggle("selected",te),z.setAttribute("aria-checked",V===q-1?"true":"false")})}),L.push(w),k.appendChild(w)}b.appendChild(k);let H=null;if(d){let q=document.createElement("div");q.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),q.appendChild(H),b.appendChild(q)}let E=document.createElement("div");E.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{n?.(),c.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(u===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let q=H?.value.trim()||void 0;await t(u,q),c.remove()}catch(q){_.disabled=!1,_.textContent=a,console.error("[CSAT Feedback] Failed to submit:",q)}}),E.appendChild(P),E.appendChild(_),b.appendChild(E),c.appendChild(b),c}function rl(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let b=null,f=document.createElement("div");f.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,y.appendChild(C);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=r,y.appendChild(k),f.appendChild(y);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=p;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=c,H.appendChild(E),H.appendChild(P);let _=document.createElement("div");_.className="persona-feedback-numbers";let q=[];for(let O=0;O<=10;O++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${O} out of 10`),j.textContent=String(O),j.dataset.rating=String(O),O<=6?j.classList.add("persona-feedback-detractor"):O<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{b=O,q.forEach((Y,be)=>{Y.classList.toggle("selected",be===O),Y.setAttribute("aria-checked",be===O?"true":"false")})}),q.push(j),_.appendChild(j)}L.appendChild(H),L.appendChild(_),f.appendChild(L);let w=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),O.appendChild(w),f.appendChild(O)}let z=document.createElement("div");z.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=i,V.addEventListener("click",()=>{n?.(),u.remove()});let te=document.createElement("button");return te.type="button",te.className="persona-feedback-btn persona-feedback-btn-submit",te.textContent=a,te.addEventListener("click",async()=>{if(b===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}te.disabled=!0,te.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(b,O),u.remove()}catch(O){te.disabled=!1,te.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),z.appendChild(V),z.appendChild(te),f.appendChild(z),u.appendChild(f),u}var Zr="persona-chat-history",cx=30*1e3,dx=641,px={"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 ux(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=px[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function sl(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 fx(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function gx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var rd=e=>!e||typeof e!="object"?{}:{...e},Wg=e=>e.map(t=>({...t,streaming:!1})),Hg=(e,t,n)=>{let o=e?.markdown?Yo(e.markdown):null,r=kr(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let d=zn()!==null,p;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});p=r?r(c):c}else if(o){let c=s.streaming?Jp(a):a,u=o(c);p=r&&d?r(u):u}else p=Rn(a);return p}};function Bg(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=re(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var mx=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},hx=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:mx(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),al=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Nr(t),r=o.features;o=ra(o);let s=sa.getForInstance(o.plugins),{plugin:a,teardown:i}=cg();o.components&&Mn.registerAll(o.components);let d=kg(),c=o.persistState===!1?null:o.storageAdapter??Zi(),u={},b=null,f=!1,y=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:x}=g;return x&&(f=!0),h}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(c?.load)try{let l=c.load();if(l&&typeof l.then=="function")b=l.then(g=>y(g??{messages:[],metadata:{}}));else{let h=y(l??{messages:[],metadata:{}});h.metadata&&(u=rd(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=y({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let C=()=>u,k=l=>{u=l({...u})??{},Pl()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[aa],H=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ur.message,ur.messageAndClick],E=ia({parsers:L,handlers:H,getSessionMetadata:C,updateSessionMetadata:k,emit:d.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let P=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,q=o.autoFocusInput??!1,w=_,z=P,V=o.layout?.header?.layout,te=!1,O=()=>Ho(o),j=()=>P||O(),Y=O()?!1:P?_:!0,be=!1,ve=null,Be=()=>{be=!0,ve&&clearTimeout(ve),ve=setTimeout(()=>{be&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),be=!1)},1e4)},se=Hg(o,E,Be),he=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,de=o.features?.showEventStreamToggle??!1,Z=o.features?.scrollToBottom??{},ue=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Se=de?new ea(ye):null,lt=o.features?.eventStream?.maxEvents??2e3,Ee=de?new Zs(lt,Se):null,De=de?new ta:null,Ne=null,qe=!1,Me=null,ce=0;Se?.open().then(()=>Ee?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Le={onCopy:l=>{d.emit("message:copy",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{d.emit("message:feedback",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},st=o.statusIndicator??{},xt=l=>l==="idle"?st.idleText??Bt.idle:l==="connecting"?st.connectingText??Bt.connecting:l==="connected"?st.connectedText??Bt.connected:l==="error"?st.errorText??Bt.error:l==="paused"?st.pausedText??Bt.paused:l==="resuming"?st.resumingText??Bt.resuming:Bt[l];function Lt(l,g,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=g,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=g}let Tt=Gf({config:o,showClose:j()}),{wrapper:Oe,panel:pe,pillRoot:et}=Tt.shell,Ie=Tt.panelElements,{container:ge,body:ie,messagesWrapper:Re,suggestions:ct,textarea:fe,sendButton:Ae,sendButtonWrapper:ne,composerForm:T,statusText:N,introTitle:v,introSubtitle:I,closeButton:M,iconHolder:W,headerTitle:G,headerSubtitle:D,header:U,footer:Q,actionsRow:Ge,rightActions:We}=Ie,Ye=Ie.leftActions,rt=Ie.setSendButtonMode,K=Ie.micButton,Ue=Ie.micButtonWrapper,Ce=Ie.attachmentButton,ze=Ie.attachmentButtonWrapper,_e=Ie.attachmentInput,Dt=Ie.attachmentPreviewsContainer;ge.classList.add("persona-relative"),ie.classList.add("persona-relative");let ml=12,Do=()=>Z.label??"",pa=()=>Z.iconName??"arrow-down",ua=()=>Z.enabled!==!1,dn=()=>ue.mode??"anchor-top",no=()=>dn()==="follow"||dn()==="anchor-top"&&cs,wd=()=>ue.anchorTopOffset??16,Sm=()=>ue.restorePosition??"bottom",Ad=()=>ue.pauseOnInteraction===!0,Sd=()=>ue.showActivityWhilePinned!==!1,Td=()=>ue.announce===!0,Rt=m("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Rt.type="button",Rt.style.display="none",Rt.setAttribute("data-persona-scroll-to-bottom","true");let es=m("span","persona-flex persona-items-center"),hl=m("span",""),Oo=m("span","");Oo.setAttribute("data-persona-scroll-to-bottom-count",""),Oo.style.display="none",Rt.append(es,hl,Oo),ge.appendChild(Rt);let oo=m("div","persona-stream-anchor-spacer");oo.setAttribute("aria-hidden","true"),oo.setAttribute("data-persona-anchor-spacer",""),oo.style.flexShrink="0",oo.style.pointerEvents="none",oo.style.height="0px",ie.appendChild(oo);let No=m("div","persona-sr-only");No.setAttribute("aria-live","polite"),No.setAttribute("aria-atomic","true"),No.setAttribute("role","status"),No.setAttribute("data-persona-live-region",""),Object.assign(No.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ge.appendChild(No);let ts=null,fa=null,Md=l=>{!Td()||!l||(fa=l,ts===null&&(ts=setTimeout(()=>{ts=null,fa&&Td()&&(No.textContent=fa),fa=null},400)))},fr=()=>{let g=Q.style.display==="none"?0:Q.offsetHeight;Rt.style.bottom=`${g+ml}px`};fr();let Ed=()=>{let l=!!Do();Rt.setAttribute("aria-label",Do()||"Jump to latest"),Rt.title=Do(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),es.innerHTML="";let g=re(pa(),"14px","currentColor",2);g?(es.appendChild(g),es.style.display=""):es.style.display="none",hl.textContent=Do(),hl.style.display=l?"":"none"};Ed();let Mt=null,nn=null,kd=null,Pd=s.find(l=>l.renderHeader);if(Pd?.renderHeader){let l=Pd.renderHeader({config:o,defaultRenderer:()=>{let g=Zn({config:o,showClose:j()});return sr(ge,g,o),g.header},onClose:()=>ft(!1,"user")});if(l){let g=ge.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),U=l,Tt.header.element=l)}}let yl=()=>{if(!Ee)return;if(qe=!0,!Ne&&Ee&&(Ne=gg({buffer:Ee,getFullHistory:()=>Ee.getAllFromStore(),onClose:()=>ns(),config:o,plugins:s,getThroughput:()=>De?.getMetric()??{status:"idle"}})),Ne&&(ie.style.display="none",Q.parentNode?.insertBefore(Ne.element,Q),Ne.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&tt.classList.add(h))}let l=()=>{if(!qe)return;let g=Date.now();g-ce>=200&&(Ne?.update(),ce=g),Me=requestAnimationFrame(l)};ce=0,Me=requestAnimationFrame(l),rn(),d.emit("eventStream:opened",{timestamp:Date.now()})},ns=()=>{if(qe){if(qe=!1,Ne&&Ne.element.remove(),ie.style.display="",tt){tt.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&tt.classList.remove(g))}Me!==null&&(cancelAnimationFrame(Me),Me=null),rn(),d.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(de){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");tt=m("button",g),tt.style.width="28px",tt.style.height="28px",tt.style.color=Xt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let h=re("activity","18px","currentColor",1.5);h&&tt.appendChild(h);let x=Ie.clearChatButtonWrapper,A=Ie.closeButtonWrapper,R=x||A;R&&R.parentNode===U?U.insertBefore(tt,R):U.appendChild(tt),tt.addEventListener("click",()=>{qe?ns():yl()})}let Tm=l=>{let g=o.attachments;if(!g?.enabled)return;let h=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let A=l.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):l.insertBefore(h,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let A=m("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(g.allowedTypes??Xn).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(A)}},Ld=s.find(l=>l.renderComposer);if(Ld?.renderComposer){let l=o.composer,g=Ld.renderComposer({config:o,defaultRenderer:()=>qr({config:o}).footer,onSubmit:h=>{if(!$||$.isStreaming())return;let x=h.trim(),A=Mt?.hasAttachments()??!1;if(!x&&!A)return;ap();let R;A&&(R=[],R.push(...Mt.getContentParts()),x&&R.push(So(x))),$.sendMessage(x,{contentParts:R}),A&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{_e?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{kd?.()}:void 0});g&&(Tt.replaceComposer(g),Q=Tt.composer.footer)}let Mm=l=>{let g=(...me)=>{for(let ae of me){let we=l.querySelector(ae);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),X=l.querySelector("[data-persona-composer-status]");h&&(T=h),x&&(fe=x),A&&(Ae=A),R&&(K=R,Ue=R.parentElement),X&&(N=X);let F=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(ct=F);let J=g("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Ce=J,ze=J.parentElement),_e=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Dt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(Ge=le),Ye=g(".persona-widget-composer__left-actions")};Tm(Q),Mm(Q);let ro=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(ro&&(Re.style.maxWidth=ro,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%"),ro&&T&&!O()&&(T.style.maxWidth=ro,T.style.marginLeft="auto",T.style.marginRight="auto"),ro&&ct&&!O()&&(ct.style.maxWidth=ro,ct.style.marginLeft="auto",ct.style.marginRight="auto"),ro&&Dt&&!O()&&(Dt.style.maxWidth=ro,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),o.attachments?.enabled&&_e&&Dt){Mt=nr.fromConfig(o.attachments),Mt.setPreviewsContainer(Dt),_e.addEventListener("change",h=>{let x=h.target;Mt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,g=Bg(l);ge.appendChild(g)}let Em=()=>nn?.prefetch();if(o.contextMentions?.enabled&&fe&&(nn=tf({config:o,textarea:fe,anchor:T??fe,getMessages:()=>$.getMessages(),liveRegionHost:ge}),nn)){let l=fe;l.parentElement?.insertBefore(nn.contextRow,l);let g=nn.affordanceButtons;for(let h=g.length-1;h>=0;h--){let x=g[h];Ye?Ye.insertBefore(x,Ye.firstChild):T?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Re;case"footer-top":return ct;case"composer":return T;case"footer-bottom":return N;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")U.insertBefore(A,U.firstChild);else if(x==="header-right")U.appendChild(A);else{let R=U.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(A,R.nextSibling):U.appendChild(A)}break;case"body-top":{let R=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(A):ie.insertBefore(A,ie.firstChild);break}case"body-bottom":ie.appendChild(A);break;case"footer-top":ct.replaceWith(A);break;case"footer-bottom":N.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(l))if(A)try{let R=A({config:o,defaultContent:()=>g(x)});R&&h(x,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,R)}})();let Rd=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-bubble-type");if(R==="reasoning")Kr.has(A)?Kr.delete(A):Kr.add(A),eg(A,x);else if(R==="tool")Gr.has(A)?Gr.delete(A):Gr.add(A),tg(A,x,o);else if(R==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=ir.get(A)??F;ir.set(A,!J),sg(A,x,o)}jo.delete(A)};Re.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rd(l))}),Re.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rd(l))}),Re.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let h=Re.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),R=Ef(A);!R||R===A||(g.setData("text/plain",R),l.preventDefault())});let bl=new Map,Id=null,Wd="idle",km={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Pm=(l,g)=>{let{icon:h,label:x}=km[g];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let A=re(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},Hd=()=>{Re.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Pm(g,x&&x===Id?Wd:"idle")})};Re.addEventListener("click",l=>{let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let R=h.getAttribute("data-action");if(R==="copy"){let F=$.getMessages().find(J=>J.id===A);if(F&&Le.onCopy){let J=F.content||"";navigator.clipboard.writeText(J).then(()=>{h.classList.add("persona-message-action-success");let le=re("check",14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let me=re("copy",14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me))},2e3)}).catch(le=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",le)}),Le.onCopy(F)}}else if(R==="read-aloud")$.toggleReadAloud(A);else if(R==="upvote"||R==="downvote"){let F=(bl.get(A)??null)===R,J=R==="upvote"?"thumbs-up":"thumbs-down";if(F){bl.delete(A),h.classList.remove("persona-message-action-active");let le=re(J,14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le))}else{let le=R==="upvote"?"downvote":"upvote",me=x.querySelector(`[data-action="${le}"]`);if(me){me.classList.remove("persona-message-action-active");let nt=re(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(me.innerHTML="",me.appendChild(nt))}bl.set(A,R),h.classList.add("persona-message-action-active");let ae=re(J,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ae)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ke=$.getMessages().find(gt=>gt.id===A);Ke&&Le.onFeedback&&Le.onFeedback({type:R,messageId:Ke.id,message:Ke})}}}),Re.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-approval-action");if(!R)return;let X=R==="approve"?"approved":"denied",J=$.getMessages().find(me=>me.id===A);if(!J?.approval)return;let le=x.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?$.resolveWebMcpApproval(A,X):$.resolveApproval(J.approval,X)});let Qe=null,os=null,rs=()=>{},ss="none",ga=null,yn={artifacts:[],selectedId:null},On=!1,bn=!1,as=!1,gr=!1,Bd=()=>gr||yn.artifacts.some(l=>In(o.features?.artifacts,l)==="panel"),ma=()=>yn.artifacts.length>0&&!On&&Bd(),pt={current:null},vl=(l,g)=>{let h=$.getArtifactById(g),x=h?.markdown,A=h?.title||"artifact",R=h?.file,X=h?.artifactType??"markdown";if(!x){let le=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(le){let ae=$.getMessages().find(we=>we.id===le);if(ae?.rawContent)try{let we=JSON.parse(ae.rawContent);x=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(R=we.props.file),!h&&typeof we?.props?.artifactType=="string"&&(X=we.props.artifactType)}catch{}}}return{markdown:x,title:A,file:R,artifactType:X}};Re.addEventListener("click",l=>{let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:R,title:X,file:F}=vl(h,x);if(!R)return;let{filename:J,mime:le,content:me}=cf({title:X,markdown:R,file:F}),ae=new Blob([me],{type:le}),we=URL.createObjectURL(ae),Ke=document.createElement("a");Ke.href=we,Ke.download=J,Ke.click(),URL.revokeObjectURL(we)}),Re.addEventListener("click",l=>{let h=l.target.closest("[data-artifact-custom-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let A=h.closest("[data-artifact-inline]"),R=A?null:h.closest("[data-open-artifact]"),X=A?A.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,J=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===x);if(!J)return;let{markdown:le,title:me,file:ae,artifactType:we}=vl(h,X??""),Ke={artifactId:X,title:me,artifactType:we,markdown:le,file:ae};try{Promise.resolve(J.onClick(Ke)).catch(()=>{})}catch{}}),Re.addEventListener("click",l=>{let h=l.target.closest("[data-copy-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let A=$.getArtifactById(x),R="";if(A)R=Vs(A);else{let{markdown:X,file:F,artifactType:J}=vl(h,x);J==="markdown"&&(R=Vs({id:x,artifactType:"markdown",status:"complete",markdown:X??"",...F?{file:F}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let X=re("check",16,"currentColor",2);X&&(h.replaceChildren(X),setTimeout(()=>{let F=re("copy",16,"currentColor",2);F&&h.replaceChildren(F)},1500))}).catch(()=>{})}),Re.addEventListener("click",l=>{let h=l.target.closest("[data-expand-artifact-inline]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(On=!1,gr=!0,bn=!0,as=!0,$.selectArtifact(x),Nn())}),Re.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let h=g.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),On=!1,gr=!0,$.selectArtifact(x),Nn())}),Re.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let mr=Ie.composerOverlay,hr=(l,g,h)=>{let x=g.trim();if(!x||!pt.current)return;let A=l.getAttribute("data-tool-call-id")??"",R=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:R,source:h.source},bubbles:!0,composed:!0})),xo(mr,A);let X=pt.current.getMessages().find(F=>F.toolCall?.id===A);X?.agentMetadata?.awaitingLocalTool?pt.current.resolveAskUserQuestion(X,h.structured??x):pt.current.sendMessage(x)},Fo=l=>{let g=pt.current;if(!g)return;let h=l.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(A=>A.toolCall?.id===h);x&&g.persistAskUserQuestionProgress(x,{answers:Ja(l,x),currentIndex:hn(l)})},Dd=l=>Object.entries(l).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),xl=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=hn(l),h=Rr(l);if(g>=h-1)return;let x=pt.current?.getMessages().find(A=>A.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(Xa(l,x,o,g+1),Fo(l))};mr.addEventListener("click",l=>{let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let R=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),xo(mr,R);let X=pt.current?.getMessages().find(F=>F.toolCall?.id===R);X?.agentMetadata?.awaitingLocalTool&&(pt.current?.markAskUserQuestionResolved(X),pt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(A==="pick"){let R=h.getAttribute("data-option-label");if(!R)return;let X=x.getAttribute("data-multi-select")==="true",F=vo(x);if(F&&X){let J=Qo(x)[hn(x)],le=new Set(Array.isArray(J)?J:[]);le.has(R)?le.delete(R):le.add(R),Co(x,Array.from(le)),Fo(x);return}if(F){Co(x,R),Fo(x),xl(x);return}if(X){let J=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",J?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!J);let le=x.querySelector('[data-ask-user-action="submit-multi"]');le&&(le.disabled=nc(x).length===0);return}hr(x,R,{source:"pick",values:[R]});return}if(A==="submit-multi"){let R=nc(x);if(R.length===0)return;hr(x,R.join(", "),{source:"multi",values:R});return}if(A==="open-free-text"){let R=x.querySelector('[data-ask-free-text-row="true"]');R&&(R.classList.remove("persona-hidden"),R.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let X=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(vo(x)){Co(x,X.trim()),Fo(x),xl(x);return}hr(x,X,{source:"free-text"});return}if(A==="next"||A==="back"){if(!pt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=pt.current.getMessages().find(ae=>ae.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ae=Qo(x)[hn(x)];(typeof ae!="string"||ae!==J)&&Co(x,J)}let le=A==="next"?1:-1,me=hn(x)+le;Xa(x,X,o,me),Fo(x);return}if(A==="submit-all"){if(!pt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=pt.current.getMessages().find(ae=>ae.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&Co(x,J);let le=Ja(x,X);pt.current.persistAskUserQuestionProgress(X,{answers:le,currentIndex:hn(x)});let me=Dd(le);hr(x,me||"(submitted)",{source:"submit-all",structured:le});return}if(A==="skip"){if(!pt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=pt.current.getMessages().find(we=>we.toolCall?.id===R);if(!X)return;let F=vo(x),J=hn(x),le=Rr(x),me=J>=le-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),xo(mr,R),X.agentMetadata?.awaitingLocalTool&&(pt.current.markAskUserQuestionResolved(X),pt.current.resolveAskUserQuestion(X,"(dismissed)"));return}Co(x,"");let ae=x.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),me){let we=Ja(x,X),Ke=Dd(we);hr(x,Ke||"(skipped)",{source:"submit-all",structured:we});return}Xa(x,X,o,J+1),Fo(x);return}}),mr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let h=l.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(vo(x)){Co(x,A.trim()),Fo(x),xl(x);return}hr(x,A,{source:"free-text"})}});let Od=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let h=mr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),R=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];R&&(l.preventDefault(),R.click())};document.addEventListener("keydown",Od);let so=null,Ct=null,is=null,ha=null,Cl=()=>{},Nd=!1,ya="",ba="";function wl(){ha?.(),ha=null}let Fd=()=>{if(!so||!Ct)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,h=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ct.style.removeProperty("position"),Ct.style.removeProperty("left"),Ct.style.removeProperty("top"),Ct.style.removeProperty("bottom"),Ct.style.removeProperty("width"),Ct.style.removeProperty("z-index");return}let x=so.firstElementChild;if(!x||x===Ct)return;let A=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${A}px`,Ct.style.zIndex="5";let R=ed(so,g),X=x.offsetWidth+R/2-A/2;Ct.style.left=`${Math.max(0,X)}px`},va=()=>{},Lm=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>h?!1:P||Pt(o)},xa=()=>!Yt(o)||!ma()||e.classList.contains("persona-artifact-narrow-host")||Lm()||(e.ownerDocument.defaultView??window).innerWidth<dx?"none":Xc(o)?"detached":"welded",Nn=()=>{if(!Qe||!Yt(o))return;na(e,o),oa(e,o),va();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=pe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let h=ma();Qe.setVisible(h),Qe.update(yn),On?(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),Qe.backdrop?.classList.add("persona-hidden"),bn=!1,as=!1):yn.artifacts.length>0&&Bd()?(Qe.element.classList.remove("persona-hidden"),Qe.setMobileOpen(!0)):(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),Qe.backdrop?.classList.add("persona-hidden"),bn=!1,as=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Qe.setExpandToggleVisible(x),Qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Qe.setTabFade(o.features?.artifacts?.layout?.tabFade),Qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!as&&(bn=!1),bn!==Nd){let R=Qe.element;bn?(ya=R.style.width,ba=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(ya&&(R.style.width=ya),ba&&(R.style.maxWidth=ba),ya="",ba=""),Nd=bn}e.classList.toggle("persona-artifact-expanded",bn),Qe.setExpanded(bn);let A=xa();A!==ss&&(ss=A,rs()),Cl()};if(Yt(o)){pe.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),Qe=mg(o,{onSelect:h=>pt.current?.selectArtifact(h),onDismiss:()=>{On=!0,Nn()},onToggleExpand:()=>{let h=!bn,x=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(bn=h,h||(as=!1),Nn())}}),Qe.element.classList.add("persona-hidden"),so=g,g.appendChild(l),g.appendChild(Qe.element),Qe.backdrop&&pe.appendChild(Qe.backdrop),pe.appendChild(g),Cl=()=>{if(!so||!Qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){is?.(),is=null,wl(),Ct&&(Ct.remove(),Ct=null),Qe.element.style.removeProperty("width"),Qe.element.style.removeProperty("maxWidth");return}if(!Ct){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=e.ownerDocument,R=A.defaultView??window,X=F=>{if(!Qe||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;F.preventDefault(),wl();let J=F.clientX,le=Qe.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,ae=Ke=>{let gt=so.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),sn=ed(so,R),Et=nt?0:x.getBoundingClientRect().width||6,Wt=le-(Ke.clientX-J),B=Sg(Wt,gt,sn,Et,me?.resizableMinWidth,me?.resizableMaxWidth);Qe.element.style.width=`${B}px`,Qe.element.style.maxWidth="none",Fd()},we=()=>{A.removeEventListener("pointermove",ae),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),ha=null;try{x.releasePointerCapture(F.pointerId)}catch{}};ha=we,A.addEventListener("pointermove",ae),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{x.setPointerCapture(F.pointerId)}catch{}};x.addEventListener("pointerdown",X),Ct=x,so.insertBefore(x,Qe.element),is=()=>{x.removeEventListener("pointerdown",X)}}if(Ct){let x=ma();Ct.classList.toggle("persona-hidden",!x),Fd()}},va=()=>{if(!P||!Qe||(o.launcher?.sidebarMode??!1)||Pt(o)&&tn(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=R||!bg(o,P))return;let X=o.launcher?.width??o.launcherWidth??ln,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ma()?(pe.style.width=F,pe.style.maxWidth=F):(pe.style.width=X,pe.style.maxWidth=X)},typeof ResizeObserver<"u"&&(os=new ResizeObserver(()=>{Nn()}),os.observe(pe))}else pe.appendChild(ge);O()&&et&&(Ie.peekBanner&&et.appendChild(Ie.peekBanner),et.appendChild(Q)),e.appendChild(Oe),et&&e.appendChild(et);let Ca=()=>{if(O()){pe.style.width="100%",pe.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},Zt=Oe.dataset.state==="expanded",Fa=kt.expandedSize??"anchored";if(!(Zt&&Fa!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let As=o.theme?.components?.panel,_a=Eo(o),Sr=(jn,Xo)=>jn==null||jn===""?Xo:Jt(_a,jn)??jn,$a="1px solid var(--persona-border)",zl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Jo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=Sr(As?.border,$a),ge.style.borderRadius=Sr(As?.borderRadius,Jo),ge.style.boxShadow=Sr(As?.shadow,zl),ge.style.overflow="hidden";return}let l=Pt(o),g=o.launcher?.sidebarMode??!1,h=l||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,X=Eo(o),F=(kt,Zt)=>kt==null||kt===""?Zt:Jt(X,kt)??kt,J=e.ownerDocument.defaultView??window,le=o.launcher?.mobileFullscreen??!0,me=o.launcher?.mobileBreakpoint??640,ae=J.innerWidth<=me,we=le&&ae&&P,Ke=l&&le&&ae,gt=o.launcher?.position??"bottom-left",nt=gt==="bottom-left"||gt==="top-left",sn=o.launcher?.zIndex??Kt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",Wt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",B="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=A&&!we&&!Ke;ke?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let $e=ke?Et:g||we?"none":Et,Te=ke?Wt:we?"none":g?nt?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":x?"none":Wt;l&&!we&&!ke&&(Te="none",$e="none");let St=ke?B:g||we?"0":B,mt=F(R?.border,$e),Nt=F(R?.shadow,Te),ht=F(R?.borderRadius,St),Qt=xa(),Ht=Qt==="detached",Pe=Qt==="welded";e.classList.toggle("persona-artifact-detached-split",Ht),e.classList.toggle("persona-artifact-welded-split",Pe);let je="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",At=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Yt(o)&&Xc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",At);let ut=Ht||At?"none":Nt,yt=Ht?Et:Pe?"none":mt,Ze=Ht?B:ht;At&&(yt="none",Ze="0");let He=R?.borderRadius!=null&&R.borderRadius!=="",vt=At&&!He?"0":ht,zt=ie.scrollTop;e.style.cssText="",Oe.style.cssText="",pe.style.cssText="",ge.style.cssText="",ie.style.cssText="",Q.style.cssText="",qe&&(ie.style.display="none"),(h||x)&&(e.style.minWidth="0");let mn=()=>{if(zt<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===zt)return;let Zt=ie.scrollHeight-ie.clientHeight;Zt<=0||(ie.scrollTop=Math.min(zt,Zt))})};if(we){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=`
|
|
48
|
+
`,S.addEventListener("click",()=>{u=q,L.forEach((V,G)=>{let oe=G<q;V.classList.toggle("selected",oe),V.setAttribute("aria-checked",G===q-1?"true":"false")})}),L.push(S),E.appendChild(S)}v.appendChild(E);let W=null;if(d){let q=document.createElement("div");q.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),q.appendChild(W),v.appendChild(q)}let A=document.createElement("div");A.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?.(),c.remove()});let F=document.createElement("button");return F.type="button",F.className="persona-feedback-btn persona-feedback-btn-submit",F.textContent=a,F.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}F.disabled=!0,F.textContent="Submitting...";try{let q=W?.value.trim()||void 0;await t(u,q),c.remove()}catch(q){F.disabled=!1,F.textContent=a,console.error("[CSAT Feedback] Failed to submit:",q)}}),A.appendChild(k),A.appendChild(F),v.appendChild(A),c.appendChild(v),c}function pl(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let v=null,f=document.createElement("div");f.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,b.appendChild(E),f.appendChild(b);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=p;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=c,W.appendChild(A),W.appendChild(k);let F=document.createElement("div");F.className="persona-feedback-numbers";let q=[];for(let N=0;N<=10;N++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${N} out of 10`),U.textContent=String(N),U.dataset.rating=String(N),N<=6?U.classList.add("persona-feedback-detractor"):N<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{v=N,q.forEach((Z,he)=>{Z.classList.toggle("selected",he===N),Z.setAttribute("aria-checked",he===N?"true":"false")})}),q.push(U),F.appendChild(U)}L.appendChild(W),L.appendChild(F),f.appendChild(L);let S=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),N.appendChild(S),f.appendChild(N)}let V=document.createElement("div");V.className="persona-feedback-actions";let G=document.createElement("button");G.type="button",G.className="persona-feedback-btn persona-feedback-btn-skip",G.textContent=i,G.addEventListener("click",()=>{n?.(),u.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(v===null){F.classList.add("persona-feedback-shake"),setTimeout(()=>F.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let N=S?.value.trim()||void 0;await t(v,N),u.remove()}catch(N){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),V.appendChild(G),V.appendChild(oe),f.appendChild(V),u.appendChild(f),u}var rs="persona-chat-history",Ox=30*1e3,Nx=641,Fx={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function _x(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=Fx[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function ul(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function $x(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function jx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var pd=e=>!e||typeof e!="object"?{}:{...e},Qf=e=>e.map(t=>({...t,streaming:!1})),Zf=(e,t,n)=>{let o=e?.markdown?tr(e.markdown):null,r=Wr(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let d=Kn()!==null,p;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});p=r?r(c):c}else if(o){let c=s.streaming?fu(a):a,u=o(c);p=r&&d?r(u):u}else p=Hn(a);return p}};function em(e){let t=h("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=re(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=h("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var Ux=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},zx=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:Ux(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),gl=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Ur(t),r=o.features;o=pa(o);let s=ua.getForInstance(o.plugins),{plugin:a,teardown:i}=Pf();o.components&&kn.registerAll(o.components);let d=Kf(),c=o.persistState===!1?null:o.storageAdapter??al(),u={},v=null,f=!1,b=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:m,open:x}=g;return x&&(f=!0),m}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(c?.load)try{let l=c.load();if(l&&typeof l.then=="function")v=l.then(g=>b(g??{messages:[],metadata:{}}));else{let m=b(l??{messages:[],metadata:{}});m.metadata&&(u=pd(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=b({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let C=()=>u,E=l=>{u=l({...u})??{},Bl()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ga],W=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[yr.message,yr.messageAndClick],A=fa({parsers:L,handlers:W,getSessionMetadata:C,updateSessionMetadata:E,emit:d.emit,documentRef:typeof document<"u"?document:null});A.syncFromMetadata();let k=o.launcher?.enabled??!0,F=o.launcher?.autoExpand??!1,q=o.autoFocusInput??!1,S=F,V=k,G=o.layout?.header?.layout,oe=!1,N=()=>No(o),U=()=>k||N(),Z=N()?!1:k?F:!0,he=!1,ve=null,ue=()=>{he=!0,ve&&clearTimeout(ve),ve=setTimeout(()=>{he&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),he=!1)},1e4)},ne=Zf(o,A,ue),fe=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,de=o.features?.showEventStreamToggle??!1,Q=o.features?.scrollToBottom??{},me=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Ae=de?new ia(ye):null,Ee=o.features?.eventStream?.maxEvents??2e3,Se=de?new aa(Ee,Ae):null,Te=de?new la:null,Fe=null,Ue=!1,ke=null,ce=0;Ae?.open().then(()=>Se?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let We={onCopy:l=>{d.emit("message:copy",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{d.emit("message:feedback",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},ot=o.statusIndicator??{},bt=l=>l==="idle"?ot.idleText??Bt.idle:l==="connecting"?ot.connectingText??Bt.connecting:l==="connected"?ot.connectedText??Bt.connected:l==="error"?ot.errorText??Bt.error:l==="paused"?ot.pausedText??Bt.paused:l==="resuming"?ot.resumingText??Bt.resuming:Bt[l];function Lt(l,g,m,x){if(x==="idle"&&m.idleLink){l.textContent="";let M=document.createElement("a");M.href=m.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=g,M.style.color="inherit",M.style.textDecoration="none",l.appendChild(M)}else l.textContent=g}let Tt=ff({config:o,showClose:U()}),{wrapper:Oe,panel:ge,pillRoot:Ye}=Tt.shell,Be=Tt.panelElements,{container:be,body:le,messagesWrapper:He,starterSuggestions:Gt,transcriptSuggestions:ft,suggestions:vt,textarea:z,sendButton:w,sendButtonWrapper:j,composerForm:y,statusText:R,introTitle:I,introSubtitle:D,closeButton:O,iconHolder:H,headerTitle:X,headerSubtitle:ie,header:Pe,footer:we,actionsRow:rt,rightActions:nt}=Be,ze=Be.leftActions,Qe=Be.setSendButtonMode,K=Be.micButton,qe=Be.micButtonWrapper,Ne=Be.attachmentButton,Ot=Be.attachmentButtonWrapper,At=Be.attachmentInput,Jt=Be.attachmentPreviewsContainer;be.classList.add("persona-relative"),le.classList.add("persona-relative");let ba=12,so=()=>Q.label??"",Um=()=>Q.iconName??"arrow-down",zm=()=>Q.enabled!==!1,un=()=>me.mode??"anchor-top",ao=()=>un()==="follow"||un()==="anchor-top"&&ys,Pd=()=>me.anchorTopOffset??16,qm=()=>me.restorePosition??"bottom",Ld=()=>me.pauseOnInteraction===!0,Rd=()=>me.showActivityWhilePinned!==!1,Id=()=>me.announce===!0,Rt=h("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");Rt.type="button",Rt.style.display="none",Rt.setAttribute("data-persona-scroll-to-bottom","true");let ss=h("span","persona-flex persona-items-center"),Al=h("span",""),_o=h("span","");_o.setAttribute("data-persona-scroll-to-bottom-count",""),_o.style.display="none",Rt.append(ss,Al,_o),be.appendChild(Rt);let io=h("div","persona-stream-anchor-spacer");io.setAttribute("aria-hidden","true"),io.setAttribute("data-persona-anchor-spacer",""),io.style.flexShrink="0",io.style.pointerEvents="none",io.style.height="0px",le.appendChild(io);let $o=h("div","persona-sr-only");$o.setAttribute("aria-live","polite"),$o.setAttribute("aria-atomic","true"),$o.setAttribute("role","status"),$o.setAttribute("data-persona-live-region",""),Object.assign($o.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),be.appendChild($o);let as=null,va=null,Wd=l=>{!Id()||!l||(va=l,as===null&&(as=setTimeout(()=>{as=null,va&&Id()&&($o.textContent=va),va=null},400)))},br=()=>{let g=we.style.display==="none"?0:we.offsetHeight;Rt.style.bottom=`${g+ba}px`};br();let Hd=()=>{let l=!!so();Rt.setAttribute("aria-label",so()||"Jump to latest"),Rt.title=so(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ss.innerHTML="";let g=re(Um(),"14px","currentColor",2);g?(ss.appendChild(g),ss.style.display=""):ss.style.display="none",Al.textContent=so(),Al.style.display=l?"":"none"};Hd();let Mt=null,rn=null,Bd=null,Dd=s.find(l=>l.renderHeader);if(Dd?.renderHeader){let l=Dd.renderHeader({config:o,defaultRenderer:()=>{let g=no({config:o,showClose:U()});return dr(be,g,o),g.header},onClose:()=>dt(!1,"user")});if(l){let g=be.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Pe=l,Tt.header.element=l)}}let Sl=()=>{if(!Se)return;if(Ue=!0,!Fe&&Se&&(Fe=Wf({buffer:Se,getFullHistory:()=>Se.getAllFromStore(),onClose:()=>is(),config:o,plugins:s,getThroughput:()=>Te?.getMetric()??{status:"idle"}})),Fe&&(le.style.display="none",we.parentNode?.insertBefore(Fe.element,we),Fe.update()),Ze){Ze.style.boxShadow=`inset 0 0 0 1.5px ${Qt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(m=>m&&Ze.classList.add(m))}let l=()=>{if(!Ue)return;let g=Date.now();g-ce>=200&&(Fe?.update(),ce=g),ke=requestAnimationFrame(l)};ce=0,ke=requestAnimationFrame(l),an(),d.emit("eventStream:opened",{timestamp:Date.now()})},is=()=>{if(Ue){if(Ue=!1,Fe&&Fe.element.remove(),le.style.display="",Ze){Ze.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&Ze.classList.remove(g))}ke!==null&&(cancelAnimationFrame(ke),ke=null),an(),d.emit("eventStream:closed",{timestamp:Date.now()})}},Ze=null;if(de){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");Ze=h("button",g),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=Qt.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let m=re("activity","18px","currentColor",1.5);m&&Ze.appendChild(m);let x=Be.clearChatButtonWrapper,M=Be.closeButtonWrapper,P=x||M;P&&P.parentNode===Pe?Pe.insertBefore(Ze,P):Pe.appendChild(Ze),Ze.addEventListener("click",()=>{Ue?is():Sl()})}let Vm=l=>{let g=o.attachments;if(!g?.enabled)return;let m=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!m){m=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let M=l.querySelector("[data-persona-composer-form]");M?.parentNode?M.parentNode.insertBefore(m,M):l.insertBefore(m,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let M=h("input");M.type="file",M.setAttribute("data-persona-composer-attachment-input",""),M.accept=(g.allowedTypes??Zn).join(","),M.multiple=(g.maxFiles??4)>1,M.style.display="none",M.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(M)}},Od=s.find(l=>l.renderComposer);if(Od?.renderComposer){let l=o.composer,g=Od.renderComposer({config:o,defaultRenderer:()=>Xr({config:o}).footer,onSubmit:m=>{if(!_||_.isStreaming())return;let x=m.trim(),M=Mt?.hasAttachments()??!1;if(!x&&!M)return;Tp();let P;M&&(P=[],P.push(...Mt.getContentParts()),x&&P.push(ko(x))),_.sendMessage(x,{contentParts:P}),M&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{At?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Bd?.()}:void 0});g&&(Tt.replaceComposer(g),we=Tt.composer.footer)}let Km=l=>{let g=(...pe)=>{for(let ae of pe){let Ce=l.querySelector(ae);if(Ce)return Ce}return null},m=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),M=l.querySelector("[data-persona-composer-submit]"),P=l.querySelector("[data-persona-composer-mic]"),Y=l.querySelector("[data-persona-composer-status]");m&&(y=m),x&&(z=x),M&&(w=M),P&&(K=P,qe=P.parentElement),Y&&(R=Y);let $=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(vt=$);let J=g("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Ne=J,Ot=J.parentElement),At=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Jt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ee=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ee&&(rt=ee),ze=g(".persona-widget-composer__left-actions")};Vm(we),Km(we);let Ln=o.layout?.contentMaxWidth??(N()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Ln&&(He.style.maxWidth=Ln,He.style.marginLeft="auto",He.style.marginRight="auto",He.style.width="100%",Gt.style.maxWidth=Ln,ft.style.maxWidth=Ln,ft.style.marginLeft="auto",ft.style.marginRight="auto",ft.style.width="100%"),Ln&&y&&!N()&&(y.style.maxWidth=Ln,y.style.marginLeft="auto",y.style.marginRight="auto"),Ln&&vt&&!N()&&(vt.style.maxWidth=Ln,vt.style.marginLeft="auto",vt.style.marginRight="auto"),Ln&&Jt&&!N()&&(Jt.style.maxWidth=Ln,Jt.style.marginLeft="auto",Jt.style.marginRight="auto"),o.attachments?.enabled&&At&&Jt){Mt=ir.fromConfig(o.attachments),Mt.setPreviewsContainer(Jt),At.addEventListener("change",m=>{let x=m.target;Mt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,g=em(l);be.appendChild(g)}let Gm=()=>rn?.prefetch();if(o.contextMentions?.enabled&&z&&(rn=xg({config:o,textarea:z,anchor:y??z,getMessages:()=>_.getMessages(),liveRegionHost:be}),rn)){let l=z;l.parentElement?.insertBefore(rn.contextRow,l);let g=rn.affordanceButtons;for(let m=g.length-1;m>=0;m--){let x=g[m];ze?ze.insertBefore(x,ze.firstChild):y?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return be.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return He;case"footer-top":return vt;case"composer":return y;case"footer-bottom":return R;default:return null}},m=(x,M)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")Pe.insertBefore(M,Pe.firstChild);else if(x==="header-right")Pe.appendChild(M);else{let P=Pe.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(M,P.nextSibling):Pe.appendChild(M)}break;case"body-top":{let P=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");P?P.replaceWith(M):le.insertBefore(M,le.firstChild);break}case"body-bottom":le.appendChild(M);break;case"footer-top":vt.replaceWith(M);break;case"footer-bottom":R.replaceWith(M);break;default:break}};for(let[x,M]of Object.entries(l))if(M)try{let P=M({config:o,defaultContent:()=>g(x)});P&&m(x,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,P)}})();let Nd=l=>{let m=l.target.closest('button[data-expand-header="true"]');if(!m)return;let x=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let M=x.getAttribute("data-message-id");if(!M)return;let P=m.getAttribute("data-bubble-type");if(P==="reasoning")Qr.has(M)?Qr.delete(M):Qr.add(M),xf(M,x);else if(P==="tool")Zr.has(M)?Zr.delete(M):Zr.add(M),Cf(M,x,o);else if(P==="approval"){let $=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=ur.get(M)??$;ur.set(M,!J),Tf(M,x,o)}Vo.delete(M)};He.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Nd(l))}),He.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Nd(l))}),He.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let m=He.getRootNode(),x=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let M=x.toString(),P=qg(M);!P||P===M||(g.setData("text/plain",P),l.preventDefault())});let Tl=new Map,Fd=null,_d="idle",Jm={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Xm=(l,g)=>{let{icon:m,label:x}=Jm[g];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let M=re(m,14,"currentColor",2);M&&(l.innerHTML="",l.appendChild(M))},$d=()=>{He.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Xm(g,x&&x===Fd?_d:"idle")})};He.addEventListener("click",l=>{let m=l.target.closest(".persona-message-action-btn[data-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let x=m.closest("[data-actions-for]");if(!x)return;let M=x.getAttribute("data-actions-for");if(!M)return;let P=m.getAttribute("data-action");if(P==="copy"){let $=_.getMessages().find(J=>J.id===M);if($&&We.onCopy){let J=$.content||"";navigator.clipboard.writeText(J).then(()=>{m.classList.add("persona-message-action-success");let ee=re("check",14,"currentColor",2);ee&&(m.innerHTML="",m.appendChild(ee)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let pe=re("copy",14,"currentColor",2);pe&&(m.innerHTML="",m.appendChild(pe))},2e3)}).catch(ee=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ee)}),We.onCopy($)}}else if(P==="read-aloud")_.toggleReadAloud(M);else if(P==="upvote"||P==="downvote"){let $=(Tl.get(M)??null)===P,J=P==="upvote"?"thumbs-up":"thumbs-down";if($){Tl.delete(M),m.classList.remove("persona-message-action-active");let ee=re(J,14,"currentColor",2);ee&&(m.innerHTML="",m.appendChild(ee))}else{let ee=P==="upvote"?"downvote":"upvote",pe=x.querySelector(`[data-action="${ee}"]`);if(pe){pe.classList.remove("persona-message-action-active");let et=re(ee==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);et&&(pe.innerHTML="",pe.appendChild(et))}Tl.set(M,P),m.classList.add("persona-message-action-active");let ae=re(J,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(ae)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ve=_.getMessages().find(pt=>pt.id===M);Ve&&We.onFeedback&&We.onFeedback({type:P,messageId:Ve.id,message:Ve})}}}),He.addEventListener("click",l=>{let m=l.target.closest("button[data-approval-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let x=m.closest(".persona-approval-bubble");if(!x)return;let M=x.getAttribute("data-message-id");if(!M)return;let P=m.getAttribute("data-approval-action");if(!P)return;let Y=P==="approve"?"approved":"denied",J=_.getMessages().find(pe=>pe.id===M);if(!J?.approval)return;let ee=x.querySelector("[data-approval-buttons]");ee&&ee.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?_.resolveWebMcpApproval(M,Y):_.resolveApproval(J.approval,Y)});let Je=null,ls=null,cs=()=>{},ds="none",xa=null,vn={artifacts:[],selectedId:null},_n=!1,xn=!1,ps=!1,vr=!1,jd=()=>vr||vn.artifacts.some(l=>Bn(o.features?.artifacts,l)==="panel"),Ca=()=>vn.artifacts.length>0&&!_n&&jd(),lt={current:null},Ml=(l,g)=>{let m=_.getArtifactById(g),x=m?.markdown,M=m?.title||"artifact",P=m?.file,Y=m?.artifactType??"markdown";if(!x){let ee=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ee){let ae=_.getMessages().find(Ce=>Ce.id===ee);if(ae?.rawContent)try{let Ce=JSON.parse(ae.rawContent);x=Ce?.props?.markdown,M=Ce?.props?.title||M,Ce?.props?.file&&typeof Ce.props.file=="object"&&(P=Ce.props.file),!m&&typeof Ce?.props?.artifactType=="string"&&(Y=Ce.props.artifactType)}catch{}}}return{markdown:x,title:M,file:P,artifactType:Y}};He.addEventListener("click",l=>{let m=l.target.closest("[data-download-artifact]");if(!m)return;l.preventDefault(),l.stopPropagation();let x=m.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:P,title:Y,file:$}=Ml(m,x);if(!P)return;let{filename:J,mime:ee,content:pe}=Eg({title:Y,markdown:P,file:$}),ae=new Blob([pe],{type:ee}),Ce=URL.createObjectURL(ae),Ve=document.createElement("a");Ve.href=Ce,Ve.download=J,Ve.click(),URL.revokeObjectURL(Ce)}),He.addEventListener("click",l=>{let m=l.target.closest("[data-artifact-custom-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let x=m.getAttribute("data-artifact-custom-action");if(!x)return;let M=m.closest("[data-artifact-inline]"),P=M?null:m.closest("[data-open-artifact]"),Y=M?M.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,J=(M?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===x);if(!J)return;let{markdown:ee,title:pe,file:ae,artifactType:Ce}=Ml(m,Y??""),Ve={artifactId:Y,title:pe,artifactType:Ce,markdown:ee,file:ae};try{Promise.resolve(J.onClick(Ve)).catch(()=>{})}catch{}}),He.addEventListener("click",l=>{let m=l.target.closest("[data-copy-artifact]");if(!m)return;l.preventDefault(),l.stopPropagation();let x=m.getAttribute("data-copy-artifact");if(!x)return;let M=_.getArtifactById(x),P="";if(M)P=Zs(M);else{let{markdown:Y,file:$,artifactType:J}=Ml(m,x);J==="markdown"&&(P=Zs({id:x,artifactType:"markdown",status:"complete",markdown:Y??"",...$?{file:$}:{}}))}P&&navigator.clipboard.writeText(P).then(()=>{let Y=re("check",16,"currentColor",2);Y&&(m.replaceChildren(Y),setTimeout(()=>{let $=re("copy",16,"currentColor",2);$&&m.replaceChildren($)},1500))}).catch(()=>{})}),He.addEventListener("click",l=>{let m=l.target.closest("[data-expand-artifact-inline]");if(!m)return;l.preventDefault(),l.stopPropagation();let x=m.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(_n=!1,vr=!0,xn=!0,ps=!0,_.selectArtifact(x),$n())}),He.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let m=g.closest("[data-open-artifact]");if(!m)return;let x=m.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),_n=!1,vr=!0,_.selectArtifact(x),$n())}),He.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let xr=Be.composerOverlay,Cr=(l,g,m)=>{let x=g.trim();if(!x||!lt.current)return;let M=l.getAttribute("data-tool-call-id")??"",P=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:x,answers:m.structured,values:m.values??(m.source==="multi"?x.split(", "):[x]),isFreeText:P,source:m.source},bubbles:!0,composed:!0})),Ao(xr,M);let Y=lt.current.getMessages().find($=>$.toolCall?.id===M);Y?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(Y,m.structured??x):lt.current.sendMessage(x)},jo=l=>{let g=lt.current;if(!g)return;let m=l.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(M=>M.toolCall?.id===m);x&&g.persistAskUserQuestionProgress(x,{answers:ei(l,x),currentIndex:bn(l)})},Ud=l=>Object.entries(l).map(([g,m])=>`${g}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),El=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=bn(l),m=Dr(l);if(g>=m-1)return;let x=lt.current?.getMessages().find(M=>M.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(ti(l,x,o,g+1),jo(l))};xr.addEventListener("click",l=>{let m=l.target.closest("[data-ask-user-action]");if(!m)return;let x=m.closest("[data-persona-ask-sheet-for]");if(!x)return;let M=m.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),M==="dismiss"){let P=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Ao(xr,P);let Y=lt.current?.getMessages().find($=>$.toolCall?.id===P);Y?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(Y),lt.current?.resolveAskUserQuestion(Y,"(dismissed)"));return}if(M==="pick"){let P=m.getAttribute("data-option-label");if(!P)return;let Y=x.getAttribute("data-multi-select")==="true",$=wo(x);if($&&Y){let J=nr(x)[bn(x)],ee=new Set(Array.isArray(J)?J:[]);ee.has(P)?ee.delete(P):ee.add(P),So(x,Array.from(ee)),jo(x);return}if($){So(x,P),jo(x),El(x);return}if(Y){let J=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",J?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!J);let ee=x.querySelector('[data-ask-user-action="submit-multi"]');ee&&(ee.disabled=lc(x).length===0);return}Cr(x,P,{source:"pick",values:[P]});return}if(M==="submit-multi"){let P=lc(x);if(P.length===0)return;Cr(x,P.join(", "),{source:"multi",values:P});return}if(M==="open-free-text"){let P=x.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(M==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(M==="submit-free-text"){let Y=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Y.trim())return;if(wo(x)){So(x,Y.trim()),jo(x),El(x);return}Cr(x,Y,{source:"free-text"});return}if(M==="next"||M==="back"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",Y=lt.current.getMessages().find(ae=>ae.toolCall?.id===P);if(!Y)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ae=nr(x)[bn(x)];(typeof ae!="string"||ae!==J)&&So(x,J)}let ee=M==="next"?1:-1,pe=bn(x)+ee;ti(x,Y,o,pe),jo(x);return}if(M==="submit-all"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",Y=lt.current.getMessages().find(ae=>ae.toolCall?.id===P);if(!Y)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&So(x,J);let ee=ei(x,Y);lt.current.persistAskUserQuestionProgress(Y,{answers:ee,currentIndex:bn(x)});let pe=Ud(ee);Cr(x,pe||"(submitted)",{source:"submit-all",structured:ee});return}if(M==="skip"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",Y=lt.current.getMessages().find(Ce=>Ce.toolCall?.id===P);if(!Y)return;let $=wo(x),J=bn(x),ee=Dr(x),pe=J>=ee-1;if(!$){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Ao(xr,P),Y.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(Y),lt.current.resolveAskUserQuestion(Y,"(dismissed)"));return}So(x,"");let ae=x.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),pe){let Ce=ei(x,Y),Ve=Ud(Ce);Cr(x,Ve||"(skipped)",{source:"submit-all",structured:Ce});return}ti(x,Y,o,J+1),jo(x);return}}),xr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let m=l.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let x=m.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let M=m.value;if(M.trim()){if(wo(x)){So(x,M.trim()),jo(x),El(x);return}Cr(x,M,{source:"free-text"})}});let zd=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let m=xr.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),P=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];P&&(l.preventDefault(),P.click())};document.addEventListener("keydown",zd);let lo=null,xt=null,us=null,wa=null,kl=()=>{},qd=!1,Aa="",Sa="";function Pl(){wa?.(),wa=null}let Vd=()=>{if(!lo||!xt)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,m=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||m){xt.style.removeProperty("position"),xt.style.removeProperty("left"),xt.style.removeProperty("top"),xt.style.removeProperty("bottom"),xt.style.removeProperty("width"),xt.style.removeProperty("z-index");return}let x=lo.firstElementChild;if(!x||x===xt)return;let M=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${M}px`,xt.style.zIndex="5";let P=id(lo,g),Y=x.offsetWidth+P/2-M/2;xt.style.left=`${Math.max(0,Y)}px`},Ta=()=>{},Ym=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>m?!1:k||Pt(o)},Ma=()=>!Zt(o)||!Ca()||e.classList.contains("persona-artifact-narrow-host")||Ym()||(e.ownerDocument.defaultView??window).innerWidth<Nx?"none":od(o)?"detached":"welded",$n=()=>{if(!Je||!Zt(o))return;ca(e,o),da(e,o),Ta();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=ge.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let m=Ca();Je.setVisible(m),Je.update(vn),_n?(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),xn=!1,ps=!1):vn.artifacts.length>0&&jd()?(Je.element.classList.remove("persona-hidden"),Je.setMobileOpen(!0)):(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),xn=!1,ps=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Je.setExpandToggleVisible(x),Je.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Je.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Je.setTabFade(o.features?.artifacts?.layout?.tabFade),Je.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!ps&&(xn=!1),xn!==qd){let P=Je.element;xn?(Aa=P.style.width,Sa=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(Aa&&(P.style.width=Aa),Sa&&(P.style.maxWidth=Sa),Aa="",Sa=""),qd=xn}e.classList.toggle("persona-artifact-expanded",xn),Je.setExpanded(xn);let M=Ma();M!==ds&&(ds=M,cs()),kl()};if(Zt(o)){ge.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(be),Je=Hf(o,{onSelect:m=>lt.current?.selectArtifact(m),onDismiss:()=>{_n=!0,$n()},onToggleExpand:()=>{let m=!xn,x=vn.selectedId??vn.artifacts[vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:m})!==!0&&(xn=m,m||(ps=!1),$n())}}),Je.element.classList.add("persona-hidden"),lo=g,g.appendChild(l),g.appendChild(Je.element),Je.backdrop&&ge.appendChild(Je.backdrop),ge.appendChild(g),kl=()=>{if(!lo||!Je)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){us?.(),us=null,Pl(),xt&&(xt.remove(),xt=null),Je.element.style.removeProperty("width"),Je.element.style.removeProperty("maxWidth");return}if(!xt){let x=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let M=e.ownerDocument,P=M.defaultView??window,Y=$=>{if(!Je||$.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||P.innerWidth<=640)return;$.preventDefault(),Pl();let J=$.clientX,ee=Je.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,ae=Ve=>{let pt=lo.getBoundingClientRect().width,et=e.classList.contains("persona-artifact-welded-split"),ln=id(lo,P),Et=et?0:x.getBoundingClientRect().width||6,Wt=ee-(Ve.clientX-J),B=Uf(Wt,pt,ln,Et,pe?.resizableMinWidth,pe?.resizableMaxWidth);Je.element.style.width=`${B}px`,Je.element.style.maxWidth="none",Vd()},Ce=()=>{M.removeEventListener("pointermove",ae),M.removeEventListener("pointerup",Ce),M.removeEventListener("pointercancel",Ce),wa=null;try{x.releasePointerCapture($.pointerId)}catch{}};wa=Ce,M.addEventListener("pointermove",ae),M.addEventListener("pointerup",Ce),M.addEventListener("pointercancel",Ce);try{x.setPointerCapture($.pointerId)}catch{}};x.addEventListener("pointerdown",Y),xt=x,lo.insertBefore(x,Je.element),us=()=>{x.removeEventListener("pointerdown",Y)}}if(xt){let x=Ca();xt.classList.toggle("persona-hidden",!x),Vd()}},Ta=()=>{if(!k||!Je||(o.launcher?.sidebarMode??!1)||Pt(o)&&on(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,M=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(M&&x.innerWidth<=P||!Of(o,k))return;let Y=o.launcher?.width??o.launcherWidth??dn,$=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ca()?(ge.style.width=$,ge.style.maxWidth=$):(ge.style.width=Y,ge.style.maxWidth=Y)},typeof ResizeObserver<"u"&&(ls=new ResizeObserver(()=>{$n()}),ls.observe(ge))}else ge.appendChild(be);N()&&Ye&&(Be.peekBanner&&Ye.appendChild(Be.peekBanner),Ye.appendChild(we)),e.appendChild(Oe),Ye&&e.appendChild(Ye);let Ea=()=>{if(N()){ge.style.width="100%",ge.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},tn=Oe.dataset.state==="expanded",za=kt.expandedSize??"anchored";if(!(tn&&za!=="fullscreen")){be.style.background="",be.style.border="",be.style.borderRadius="",be.style.overflow="",be.style.boxShadow="";return}let Rs=o.theme?.components?.panel,qa=Ro(o),Pr=(qn,er)=>qn==null||qn===""?er:Yt(qa,qn)??qn,Va="1px solid var(--persona-border)",Xl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Zo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";be.style.background="var(--persona-surface, #ffffff)",be.style.border=Pr(Rs?.border,Va),be.style.borderRadius=Pr(Rs?.borderRadius,Zo),be.style.boxShadow=Pr(Rs?.shadow,Xl),be.style.overflow="hidden";return}let l=Pt(o),g=o.launcher?.sidebarMode??!1,m=l||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,M=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,Y=Ro(o),$=(kt,tn)=>kt==null||kt===""?tn:Yt(Y,kt)??kt,J=e.ownerDocument.defaultView??window,ee=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,ae=J.innerWidth<=pe,Ce=ee&&ae&&k,Ve=l&&ee&&ae,pt=o.launcher?.position??"bottom-left",et=pt==="bottom-left"||pt==="top-left",ln=o.launcher?.zIndex??Kt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",Wt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",B="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Le=M&&!Ce&&!Ve;Le?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let _e=Le?Et:g||Ce?"none":Et,Me=Le?Wt:Ce?"none":g?et?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":x?"none":Wt;l&&!Ce&&!Le&&(Me="none",_e="none");let St=Le?B:g||Ce?"0":B,ut=$(P?.border,_e),Nt=$(P?.shadow,Me),gt=$(P?.borderRadius,St),en=Ma(),Ht=en==="detached",Re=en==="welded";e.classList.toggle("persona-artifact-detached-split",Ht),e.classList.toggle("persona-artifact-welded-split",Re);let $e="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",wt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Zt(o)&&od(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",wt);let ct=Ht||wt?"none":Nt,mt=Ht?Et:Re?"none":ut,Xe=Ht?B:gt;wt&&(mt="none",Xe="0");let De=P?.borderRadius!=null&&P.borderRadius!=="",yt=wt&&!De?"0":gt,zt=le.scrollTop;e.style.cssText="",Oe.style.cssText="",ge.style.cssText="",be.style.cssText="",le.style.cssText="",we.style.cssText="",Ue&&(le.style.display="none"),(m||x)&&(e.style.minWidth="0");let yn=()=>{if(zt<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===zt)return;let tn=le.scrollHeight-le.clientHeight;tn<=0||(le.scrollTop=Math.min(zt,tn))})};if(Ce){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=`
|
|
49
49
|
position: fixed !important;
|
|
50
50
|
inset: 0 !important;
|
|
51
51
|
width: 100% !important;
|
|
@@ -55,9 +55,9 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
55
55
|
padding: 0 !important;
|
|
56
56
|
display: flex !important;
|
|
57
57
|
flex-direction: column !important;
|
|
58
|
-
z-index: ${
|
|
58
|
+
z-index: ${ln} !important;
|
|
59
59
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
60
|
-
`,
|
|
60
|
+
`,ge.style.cssText=`
|
|
61
61
|
position: relative !important;
|
|
62
62
|
display: flex !important;
|
|
63
63
|
flex-direction: column !important;
|
|
@@ -70,7 +70,7 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
70
70
|
padding: 0 !important;
|
|
71
71
|
box-shadow: none !important;
|
|
72
72
|
border-radius: 0 !important;
|
|
73
|
-
`,
|
|
73
|
+
`,be.style.cssText=`
|
|
74
74
|
display: flex !important;
|
|
75
75
|
flex-direction: column !important;
|
|
76
76
|
flex: 1 1 0% !important;
|
|
@@ -81,7 +81,7 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
81
81
|
overflow: hidden !important;
|
|
82
82
|
border-radius: 0 !important;
|
|
83
83
|
border: none !important;
|
|
84
|
-
`,
|
|
84
|
+
`,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",we.style.flexShrink="0",oe=!0,yn();return}let Ua=o?.launcher?.width??o?.launcherWidth??dn;if(!g&&!l)x&&m?(ge.style.width="100%",ge.style.maxWidth="100%"):(ge.style.width=Ua,ge.style.maxWidth=Ua);else if(l)if(on(o).reveal==="emerge"&&!M){let tn=on(o).width;ge.style.width=tn,ge.style.maxWidth=tn}else ge.style.width="100%",ge.style.maxWidth="100%";if(Ta(),ge.style.boxShadow=ct,ge.style.borderRadius=yt,Ht?ge.style.border="none":Re&&(ge.style.border=ut),be.style.border=mt,be.style.borderRadius=Xe,be.style.boxShadow=Ht&&!wt?$e:"",wt&&(be.style.background="transparent",le.style.background="transparent",we.style.background="transparent",we.style.borderTop="none"),Re){let kt=o.features?.artifacts?.layout;xa=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||gt}else xa=null;if(l&&!Ce&&!Le&&!Ht&&!Re&&P?.border===void 0&&(be.style.border="none",on(o).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),l&&!Ce&&Re&&P?.border===void 0&&(on(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",x&&(Oe.style.overflow="hidden"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",Ht||(ge.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",we.style.flexShrink="0"),x&&(Le||Ht||wt)&&!l&&(wt||(Oe.style.padding="var(--persona-panel-inset)"),Oe.style.background="var(--persona-panel-canvas-bg)"),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"),!g&&!x&&!l&&(Pn[pt]??Pn["bottom-right"]).split(" ").forEach(tn=>Oe.classList.add(tn)),g){let kt=o.launcher?.sidebarWidth??"420px";M?Oe.style.cssText=`
|
|
85
85
|
position: fixed !important;
|
|
86
86
|
top: var(--persona-panel-inset) !important;
|
|
87
87
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -92,8 +92,8 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
92
92
|
padding: 0 !important;
|
|
93
93
|
display: flex !important;
|
|
94
94
|
flex-direction: column !important;
|
|
95
|
-
z-index: ${
|
|
96
|
-
${
|
|
95
|
+
z-index: ${ln} !important;
|
|
96
|
+
${et?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
97
97
|
`:Oe.style.cssText=`
|
|
98
98
|
position: fixed !important;
|
|
99
99
|
top: 0 !important;
|
|
@@ -105,9 +105,9 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
105
105
|
padding: 0 !important;
|
|
106
106
|
display: flex !important;
|
|
107
107
|
flex-direction: column !important;
|
|
108
|
-
z-index: ${
|
|
109
|
-
${
|
|
110
|
-
`,
|
|
108
|
+
z-index: ${ln} !important;
|
|
109
|
+
${et?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
110
|
+
`,ge.style.cssText=`
|
|
111
111
|
position: relative !important;
|
|
112
112
|
display: flex !important;
|
|
113
113
|
flex-direction: column !important;
|
|
@@ -118,10 +118,10 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
118
118
|
min-height: 0 !important;
|
|
119
119
|
margin: 0 !important;
|
|
120
120
|
padding: 0 !important;
|
|
121
|
-
box-shadow: ${
|
|
122
|
-
border-radius: ${
|
|
123
|
-
${Ht?"border: none !important;":
|
|
124
|
-
`,
|
|
121
|
+
box-shadow: ${ct} !important;
|
|
122
|
+
border-radius: ${yt} !important;
|
|
123
|
+
${Ht?"border: none !important;":Re?`border: ${ut} !important;`:""}
|
|
124
|
+
`,ge.style.setProperty("width","100%","important"),ge.style.setProperty("max-width","100%","important"),be.style.cssText=`
|
|
125
125
|
display: flex !important;
|
|
126
126
|
flex-direction: column !important;
|
|
127
127
|
flex: 1 1 0% !important;
|
|
@@ -130,32 +130,32 @@ _Details: ${n.message}_`:o}var Ns=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
130
130
|
min-height: 0 !important;
|
|
131
131
|
max-height: 100% !important;
|
|
132
132
|
overflow: hidden !important;
|
|
133
|
-
border-radius: ${
|
|
134
|
-
border: ${
|
|
135
|
-
${Ht&&!
|
|
136
|
-
${
|
|
137
|
-
`,
|
|
133
|
+
border-radius: ${Xe} !important;
|
|
134
|
+
border: ${mt} !important;
|
|
135
|
+
${Ht&&!wt?`box-shadow: ${$e} !important;`:""}
|
|
136
|
+
${wt?"background: transparent !important;":""}
|
|
137
|
+
`,we.style.cssText=`
|
|
138
138
|
flex-shrink: 0 !important;
|
|
139
139
|
border-top: none !important;
|
|
140
140
|
padding: 8px 16px 12px 16px !important;
|
|
141
|
-
${
|
|
142
|
-
`}if(!x&&!l){let kt="max-height: -moz-available !important; max-height: stretch !important;",Zt=g?"":"padding-top: 1.25em !important;",Fa=g?"":`z-index: ${o.launcher?.zIndex??Kt} !important;`;Oe.style.cssText+=kt+Zt+Fa}mn()};Ca(),or(e,o),na(e,o),oa(e,o),rs=()=>{Ca(),or(e,o),na(e,o),oa(e,o),ga?e.style.setProperty("--persona-artifact-welded-outer-radius",ga):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",Od)}),Ve.push(()=>{ts!==null&&clearTimeout(ts)});let kn=null,Pn=null;Ve.push(()=>{kn?.(),kn=null,Pn?.(),Pn=null}),os&&Ve.push(()=>{os?.disconnect(),os=null}),Ve.push(()=>{is?.(),is=null,wl(),Ct&&(Ct.remove(),Ct=null),Qe?.element.style.removeProperty("width"),Qe?.element.style.removeProperty("maxWidth")}),de&&Ve.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),Ne?.destroy(),Ne=null,Ee?.destroy(),Ee=null,Se=null});let _o=null,_d=()=>{_o&&(_o(),_o=null),o.colorScheme==="auto"&&(_o=Fr(()=>{or(e,o)}))};_d(),Ve.push(()=>{_o&&(_o(),_o=null)}),Ve.push(i);let wa=o.features?.streamAnimation;if(wa?.type&&wa.type!=="none"){let l=Ur(wa.type,wa.plugins);l&&(Di(l,e),Ve.push(()=>Uf(e)))}let Aa=dg(ct),$o=null,$,Al=l=>{if(!$)return;let g=l??$.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?Qa(g):null;h?Aa.render(h,$,fe,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?Aa.render([],$,fe,g):Aa.render(o.suggestionChips,$,fe,g,o.suggestionChipsConfig)},vn=!1,jo=Lf(),yr=new Map,Uo=new Map,ao=new Map,Sl=0,Rm=zn()!==null,on=Li(),pn=0,io=null,un=!1,Sa=!1,lo=0,xn=null,zo=null,Tl=!1,Ta=!1,ls=null,cs=!0,Ma=!1,Ea=null,ka=!1,qo=()=>{ka=!0},Ml=null,Im=4,Pa=24,Wm=80,El=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},$d=o.voiceRecognition?.autoResume??!1,Fn=l=>{d.emit("voice:state",{active:Xe.active,source:l,timestamp:Date.now()})},Cn=()=>{k(l=>({...l,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},Hm=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=rd(u.voiceState),g=!!l.active,h=Number(l.timestamp??0);Xe.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-h<cx&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Fn("restore"),$.isVoiceActive()&&wr()}):Ha("restore"))},1e3)},Bm=()=>$?Wg($.getMessages()).filter(l=>!l.__skipPersist):[],La=null,jd=(l,g)=>{typeof console<"u"&&console.error(l,g)},kl=(l,g)=>{let h=()=>{try{let X=l();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(F=>{jd(g,F)})}catch(X){return jd(g,X),null}},x=La,A=x?x.then(()=>h()??void 0):h();if(!A)return;let R=A.finally(()=>{La===R&&(La=null)});La=R};function Pl(l){if(!c?.save)return;let h={messages:l?Wg(l):$?Bm():[],metadata:u,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};kl(()=>c.save(h),"[AgentWidget] Failed to persist state:")}let br=null,Ud=()=>Oe.querySelector("#persona-scroll-container")||ie,ds=()=>{br!==null&&(cancelAnimationFrame(br),br=null),un=!1},zd=()=>{io!==null&&(cancelAnimationFrame(io),io=null),Sa=!1,ds()},Dm=()=>vn&&Rl()&&(dn()!=="anchor-top"||Sd()),Ll=()=>{let l=Do()||"Jump to latest",g=Dm();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),lo>0?(Oo.textContent=String(lo),Oo.style.display="",Rt.setAttribute("aria-label",`${l} (${lo} new)`)):(Oo.textContent="",Oo.style.display="none",Rt.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},qd=()=>{lo!==0&&(lo=0,Ll())},Rl=()=>no()?!on.isFollowing():!Io(ie,Pa),rn=()=>{if(!ua()||qe){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==ge&&ge.appendChild(Rt),fr();let g=Hn(ie)>0&&Rl();g?Ll():qd(),Rt.style.display=g?"":"none"},ps=()=>{on.pause()&&(zd(),rn())},co=()=>{on.resume(),qd(),rn()},po=(l=!1)=>{no()&&on.isFollowing()&&(!l&&!vn||(io!==null&&(cancelAnimationFrame(io),io=null),Sa=!0,io=requestAnimationFrame(()=>{io=null,Sa=!1,on.isFollowing()&&Om(Ud(),l?220:140)})))},Vd=(l,g,h,x=()=>!0)=>{let A=l.scrollTop,R=g(),X=R-A;if(ds(),Math.abs(X)<1){un=!0,l.scrollTop=R,pn=l.scrollTop,un=!1;return}let F=performance.now();un=!0;let J=me=>1-Math.pow(1-me,3),le=me=>{if(!x()){ds();return}let ae=g();ae!==R&&(R=ae,X=R-A);let we=me-F,Ke=Math.min(we/h,1),gt=J(Ke),nt=A+X*gt;l.scrollTop=nt,pn=l.scrollTop,Ke<1?br=requestAnimationFrame(le):(l.scrollTop=R,pn=l.scrollTop,br=null,un=!1)};br=requestAnimationFrame(le)},Om=(l,g=500)=>{let h=Hn(l)-l.scrollTop;if(Math.abs(h)<1){pn=l.scrollTop;return}if(Math.abs(h)>=Wm){ds(),un=!0,l.scrollTop=Hn(l),pn=l.scrollTop,un=!1;return}Vd(l,()=>Hn(l),g,()=>on.isFollowing())},Kd=()=>{let l=Ud();un=!0,l.scrollTop=Hn(l),pn=l.scrollTop,un=!1,rn()},Gd=l=>{let g=0,h=l;for(;h&&h!==ie;)g+=h.offsetTop,h=h.offsetParent;return g},Nm=()=>{let l=ie.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??ie.ownerDocument.getSelection()},Ra=()=>Bf(Nm(),ie),Jd=()=>{if(Sm()!=="last-user-turn")return!1;let l=$?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(R=>R.role==="user");if(!g)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ie.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,Gd(x)-wd()),Hn(ie));return un=!0,ie.scrollTop=A,pn=ie.scrollTop,un=!1,dn()==="follow"&&!Io(ie,Pa)&&on.pause(),rn(),!0},Xd=l=>{oo.style.height=`${Math.max(0,Math.round(l))}px`,xn&&(xn.spacerHeight=Math.max(0,l))},us=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null),ds(),xn=null,oo.style.height="0px"},Yd=l=>{zo!==null&&cancelAnimationFrame(zo),zo=requestAnimationFrame(()=>{zo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ie.querySelector(`[data-message-id="${g}"]`);if(!h)return;let x=Gd(h),A=xn?.spacerHeight??0,R=ie.scrollHeight-A,{targetScrollTop:X,spacerHeight:F}=Df({anchorOffsetTop:x,topOffset:wd(),viewportHeight:ie.clientHeight,contentHeight:R});xn={initialSpacerHeight:F,contentHeightAtAnchor:R,spacerHeight:F},Xd(F),Vd(ie,()=>X,220)})},Fm=()=>{if(no()){if(!on.isFollowing()||Io(ie,1))return;po(!vn);return}if(xn&&xn.initialSpacerHeight>0){let l=ie.scrollHeight-xn.spacerHeight,g=Of({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:l});g!==xn.spacerHeight&&Xd(g)}rn()},_m=l=>{let g=dn();g==="follow"?(co(),po(!0)):g==="anchor-top"&&(cs=!1,Ma=!0,ka=!1,Ea=l,Yd(l))},$m=()=>{if(dn()==="anchor-top"){if(Ma){cs=!1;return}cs=!0,us(),co(),po(!0)}},jm=l=>{if(dn()!=="anchor-top"||!Ma||ka||Ra())return;let g=ls===null;for(let h of l){if(!g){h.id===ls&&(g=!0);continue}if(Hf(h)){if(h.id===Ea)return;Ea=h.id,Yd(h.id);return}}},Um=l=>{let g=new Map;l.forEach(h=>{let x=El.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(d.emit("assistant:message",h),!Ta&&(dn()!=="anchor-top"||Sd())&&Rl()&&(lo+=1,Ll(),rn(),Md(lo===1?"1 new message below.":`${lo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&d.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&d.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):d.emit("approval:requested",{approval:h.approval,message:h}))}),El.clear(),g.forEach((h,x)=>{El.set(x,h)})},Ia=(l,g)=>{let h=g==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",R=x?.maxWidth??(A==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${g}`,`persona-message-width-${A}`),l.classList.toggle("persona-justify-end",g==="user"),l.setAttribute("data-message-role",g),l.setAttribute("data-message-width",A),l.style.setProperty("--persona-message-row-max-width",R)},Vo=(l,g)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${l}`,h.setAttribute("data-wrapper-id",l),Ia(h,g),h},zm=(l,g,h)=>{let x=document.createElement("div"),R=(()=>{let B=s.find(ke=>ke.renderLoadingIndicator);if(B?.renderLoadingIndicator)return B.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(B,ke)=>ke==null?!1:typeof ke=="string"?(B.textContent=ke,!0):(B.appendChild(ke),!0),F=new Set,J=new Map,le=new Set,me=s.some(B=>B.renderAskUserQuestion),ae=[],we=[],Ke=o.enableComponentStreaming!==!1,gt=o.approval!==!1,nt=[];if(g.forEach(B=>{F.add(B.id),J.set(B.id,B.role);let ke=me&&Vn(B),$e=gt&&B.variant==="approval"&&!!B.approval,Te=!ke&&B.role==="assistant"&&!B.variant&&Ke&&la(B);!$e&&ao.has(B.id)&&(l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),ao.delete(B.id)),!Te&&Uo.has(B.id)&&(l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),Uo.delete(B.id));let St=Vn(B)?`:${B.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${B.agentMetadata?.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",mt=Pf(B,Sl)+St,Nt=ke||$e||Te?null:Rf(jo,B.id,mt);if(Nt){x.appendChild(Nt.cloneNode(!0)),Vn(B)&&B.toolCall?.id&&B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(le.add(B.toolCall.id),Ir(B,o,Ie.composerOverlay));return}let ht=null,Qt=s.find(je=>!!(B.variant==="reasoning"&&je.renderReasoning||B.variant==="tool"&&je.renderToolCall||!B.variant&&je.renderMessage)),Ht=o.layout?.messages;if(Vn(B)&&B.agentMetadata?.askUserQuestionAnswered===!0){yr.delete(B.id),l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime");return}if(Is(B)&&o.features?.suggestReplies?.enabled!==!1)return;if(Vn(B)&&o.features?.askUserQuestion?.enabled!==!1){let je=s.find(jt=>typeof jt.renderAskUserQuestion=="function");if(je&&pt.current){let jt=yr.get(B.id),Ut=jt!==mt,At=null;if(Ut){let{payload:Ze,complete:He}=Kn(B),vt=B.id,zt=()=>pt.current?.getMessages().find(mn=>mn.id===vt);At=je.renderAskUserQuestion({message:B,payload:Ze,complete:He,resolve:mn=>{let ws=zt();ws&&pt.current?.resolveAskUserQuestion(ws,mn)},dismiss:()=>{let mn=zt();mn?.agentMetadata?.awaitingLocalTool&&(pt.current?.markAskUserQuestionResolved(mn),pt.current?.resolveAskUserQuestion(mn,"(dismissed)"))},config:o})}let ut=jt!=null;if(Ut&&At===null&&!ut){B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(le.add(B.toolCall.id),Ir(B,o,Ie.composerOverlay));return}let yt=Vo(B.id,B.role);yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),x.appendChild(yt),ae.push({messageId:B.id,fingerprint:mt,bubble:At});return}else{B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(le.add(B.toolCall.id),Ir(B,o,Ie.composerOverlay));return}}else if($e){let je=s.find(ut=>typeof ut.renderApproval=="function")??a,Ut=ao.get(B.id)!==mt,At=null;if(Ut&&je?.renderApproval){let ut=B.id,yt=(Ze,He)=>{let vt=pt.current?.getMessages().find(zt=>zt.id===ut);vt?.approval&&(vt.approval.toolType==="webmcp"?pt.current?.resolveWebMcpApproval(vt.id,Ze):pt.current?.resolveApproval(vt.approval,Ze,He))};At=je.renderApproval({message:B,defaultRenderer:()=>Ki(B,o),config:o,approve:Ze=>yt("approved",Ze),deny:Ze=>yt("denied",Ze)})}if(Ut&&At===null)l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),ao.delete(B.id),ht=Ki(B,o);else{let ut=Vo(B.id,B.role);ut.setAttribute("data-approval-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),x.appendChild(ut),nt.push({messageId:B.id,fingerprint:mt,bubble:At});return}}else if(Qt)if(B.variant==="reasoning"&&B.reasoning&&Qt.renderReasoning){if(!he)return;ht=Qt.renderReasoning({message:B,defaultRenderer:()=>Uc(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&Qt.renderToolCall){if(!ee)return;ht=Qt.renderToolCall({message:B,defaultRenderer:()=>qc(B,o),config:o})}else Qt.renderMessage&&(ht=Qt.renderMessage({message:B,defaultRenderer:()=>{let je=Vr(B,h,Ht,o.messageActions,Le,{loadingIndicatorRenderer:R,widgetConfig:o});return B.role!=="user"&&td(je,B,o,$),je},config:o}));if(!ht&&Te){let je=nl(B);if(je){let jt=Uo.get(B.id),Ut=jt!==mt,At=o.wrapComponentDirectiveInBubble!==!1&&Mn.getOptions(je.component)?.bubbleChrome!==!1,ut=null;if(Ut){let yt=tl(je,{config:o,message:B,transform:h});if(yt&&je.component==="PersonaArtifactInline"){let Ze=yt.hasAttribute("data-artifact-inline")?yt:yt.querySelector("[data-artifact-inline]"),He=Ze?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,zt=He?l.querySelector(`#wrapper-${B.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;Ze&&zt&&zt!==Ze&&Af(zt)&&(Ze===yt?yt=zt:Ze.replaceWith(zt))}if(yt)if(At){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${B.id}`,Ze.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ze.appendChild(He)}Ze.appendChild(yt),ut=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${B.id}`,Ze.setAttribute("data-message-id",B.id),Ze.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ze.appendChild(He)}Ze.appendChild(yt),ut=Ze}}if(ut||jt!=null){let yt=Vo(B.id,B.role);yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),x.appendChild(yt),we.push({messageId:B.id,fingerprint:mt,bubble:ut});return}}}if(!ht)if(B.variant==="reasoning"&&B.reasoning){if(!he)return;ht=Uc(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!ee)return;ht=qc(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;ht=Ki(B,o)}else{let je=o.layout?.messages;je?.renderUserMessage&&B.role==="user"?ht=je.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):je?.renderAssistantMessage&&B.role==="assistant"?ht=je.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):ht=Vr(B,h,je,o.messageActions,Le,{loadingIndicatorRenderer:R,widgetConfig:o}),B.role!=="user"&&ht&&td(ht,B,o,$)}let Pe=Vo(B.id,B.role);Pe.appendChild(ht),If(jo,B.id,mt,Pe),x.appendChild(Pe)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let $e=ke.getAttribute("data-persona-ask-sheet-for");$e&&!le.has($e)&&xo(Ie.composerOverlay,$e)}),o.features?.toolCallDisplay?.grouped){let B=[],ke=[],$e=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Te=>{if(Te.variant==="tool"&&Te.toolCall&&ee){ke.push(Te);return}Te.variant==="reasoning"&&!he||((ke.length>1||$e&&ke.length>0)&&B.push(ke),ke=[])}),(ke.length>1||$e&&ke.length>0)&&B.push(ke),B.forEach(Te=>{let St=Te.map(je=>Array.from(x.children).find(jt=>jt instanceof HTMLElement&&jt.getAttribute("data-wrapper-id")===je.id)).filter(je=>!!je);if(St.length<($e?1:2))return;let mt=Vo(`tool-group-${Te[0].id}`,"assistant");mt.setAttribute("data-persona-tool-group-row","true");let Nt=document.createElement("div");Nt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Nt.setAttribute("data-persona-tool-group","true");let ht=document.createElement("div");ht.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ht.id=`tool-group-summary-${Te[0].id}`;let Qt=`Called ${Te.length} ${Te.length===1?"tool":"tools"}`,Ht=o.toolCall?.renderGroupedSummary?.({messages:Te,toolCalls:Te.map(je=>je.toolCall).filter(je=>!!je),defaultSummary:Qt,config:o});X(ht,Ht)||(ht.textContent=Qt);let Pe=document.createElement("div");Pe.className="persona-tool-group-stack persona-flex persona-flex-col",Pe.id=`tool-group-stack-${Te[0].id}`,Pe.setAttribute("data-persona-tool-group-stack","true"),Nt.appendChild(ht),$e||Nt.appendChild(Pe),mt.appendChild(Nt),St[0].before(mt),St.forEach((je,jt)=>{if($e){je.remove();return}je.style.setProperty("--persona-message-row-max-width","100%");let Ut=document.createElement("div");Ut.className="persona-tool-group-item persona-relative",Ut.setAttribute("data-persona-tool-group-item","true"),jt<St.length-1&&Ut.setAttribute("data-persona-tool-group-connector","true"),Ut.appendChild(je),Pe.appendChild(Ut)})})}Wf(jo,F);let sn=g.some(B=>B.role==="assistant"&&B.streaming),Et=g[g.length-1],Wt=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(vn&&g.some(B=>B.role==="user")&&!sn&&!Wt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ar},ke=s.find(Te=>Te.renderLoadingIndicator),$e=null;if(ke?.renderLoadingIndicator&&($e=ke.renderLoadingIndicator(B)),$e===null&&o.loadingIndicator?.render&&($e=o.loadingIndicator.render(B)),$e===null&&($e=ar()),$e){let Te=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,mt=o.layout?.messages?.layout??"bubble";Te.className=St?$c("assistant",mt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Te.setAttribute("data-typing-indicator","true"),St&&(Te.style.color="var(--persona-message-assistant-text, var(--persona-text))",mt!=="flat"&&(Te.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Te.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Te.appendChild($e);let Nt=Vo("typing-indicator","assistant");Nt.appendChild(Te),x.appendChild(Nt)}}if(!vn&&g.length>0){let B=g[g.length-1],ke={config:o,lastMessage:B,messageCount:g.length},$e=s.find(St=>St.renderIdleIndicator),Te=null;if($e?.renderIdleIndicator&&(Te=$e.renderIdleIndicator(ke)),Te===null&&o.loadingIndicator?.renderIdle&&(Te=o.loadingIndicator.renderIdle(ke)),Te){let St=document.createElement("div"),mt=o.loadingIndicator?.showBubble!==!1;St.className=mt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(Te);let Nt=Vo("idle-indicator","assistant");Nt.appendChild(St),x.appendChild(Nt)}}if(Zp(x),Pi(l,x),Jl(l),ae.length>0)for(let{messageId:B,fingerprint:ke,bubble:$e}of ae){let Te=l.querySelector(`#wrapper-${B}`);Te&&(Ia(Te,J.get(B)??"assistant"),$e!==null&&(Te.replaceChildren($e),Te.setAttribute("data-bubble-fp",ke),yr.set(B,ke)))}if(yr.size>0)for(let B of yr.keys())F.has(B)||yr.delete(B);if(we.length>0)for(let{messageId:B,fingerprint:ke,bubble:$e}of we){let Te=l.querySelector(`#wrapper-${B}`);Te&&(Ia(Te,J.get(B)??"assistant"),$e!==null&&(Te.replaceChildren($e),Te.setAttribute("data-bubble-fp",ke),Uo.set(B,ke)))}if(Uo.size>0)for(let B of Uo.keys())F.has(B)||Uo.delete(B);if(nt.length>0)for(let{messageId:B,fingerprint:ke,bubble:$e}of nt){let Te=l.querySelector(`#wrapper-${B}`);Te&&(Ia(Te,J.get(B)??"assistant"),$e!==null&&(Te.replaceChildren($e),Te.setAttribute("data-bubble-fp",ke),ao.set(B,ke)))}if(ao.size>0)for(let B of ao.keys())F.has(B)||ao.delete(B)},fs=(l,g,h)=>{zm(l,g,h),Hd()},gs=null,qm=()=>{if(gs)return;let l=h=>{let x=h.composedPath();x.includes(Oe)||et&&x.includes(et)||ft(!1,"user")};gs=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Qd=()=>{if(!gs)return;(e.ownerDocument??document).removeEventListener("pointerdown",gs,!0),gs=null};Ve.push(()=>Qd());let ms=null,Vm=()=>{if(ms)return;let l=h=>{h.key==="Escape"&&(h.isComposing||ft(!1,"user"))};ms=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Zd=()=>{if(!ms)return;(e.ownerDocument??document).removeEventListener("keydown",ms,!0),ms=null};Ve.push(()=>Zd());let hs=!1,ep=new Set,Km=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},vr=()=>{if(!O())return;let l=Ie.peekBanner,g=Ie.peekTextNode;if(!l||!g)return;if(Y){l.classList.remove("persona-pill-peek--visible");return}let h=$?.getMessages()??[],x;for(let Et=h.length-1;Et>=0;Et--){let Wt=h[Et];if(Wt.role==="assistant"&&Wt.content){x=Wt;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,R=!!x.streaming,X=Km(),F=Wi(X),J=F.type!=="none"?Ur(F.type,X?.plugins):null,le=J?.isAnimating?.(x)===!0,me=J!==null&&(R||le);me&&J&&!ep.has(J.name)&&(Di(J,e),ep.add(J.name));let ae=me&&J?.containerClass?J.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==ae&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),ae&&we!==ae&&(g.classList.add(ae),g.dataset.personaPeekStreamClass=ae),me?(g.style.setProperty("--persona-stream-step",`${F.speed}ms`),g.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ke=me?Hi(A,F.buffer,J,x,R):A;if(me&&F.placeholder==="skeleton"&&R&&(!Ke||!Ke.trim())){let Et=document.createElement("div"),Wt=Xs();Wt.classList.add("persona-pill-peek__skeleton"),Et.appendChild(Wt),Pi(g,Et)}else{let Et=Math.max(0,Ke.length-100),Wt=Ke.length>100?Ke.slice(-100):Ke,B=Rn(Wt);if(!me||!J){let ke=Ke.length>100?`\u2026${Wt}`:Wt;g.textContent!==ke&&(g.textContent=ke)}else{let ke=B;(J.wrap==="char"||J.wrap==="word")&&(ke=Js(B,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Et}));let $e=document.createElement("div");if($e.innerHTML=ke,J.useCaret&&Wt.length>0){let Te=Bi(),St=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),mt=St[St.length-1];mt?.parentNode?mt.parentNode.insertBefore(Te,mt.nextSibling):$e.appendChild(Te)}Pi(g,$e),J.onAfterRender?.({container:g,bubble:l,messageId:x.id,message:x,speed:F.speed,duration:F.duration})}}let sn=vn||hs;l.classList.toggle("persona-pill-peek--visible",sn)};if(O()){let l=Ie.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),ft(!0,"user")};l.addEventListener("pointerdown",x),Ve.push(()=>{l.removeEventListener("pointerdown",x)})}let g=()=>{hs||(hs=!0,vr())},h=()=>{hs&&(hs=!1,vr())};pe.addEventListener("pointerenter",g),pe.addEventListener("pointerleave",h),Ve.push(()=>{pe.removeEventListener("pointerenter",g),pe.removeEventListener("pointerleave",h)}),et&&(et.addEventListener("pointerenter",g),et.addEventListener("pointerleave",h),Ve.push(()=>{et.removeEventListener("pointerenter",g),et.removeEventListener("pointerleave",h)}))}let Gm=l=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",x=g.bottomOffset??"16px",A=g.collapsedMaxWidth,R=g.expandedMaxWidth??"880px",X=g.expandedTopOffset??"5vh",F=g.modalMaxWidth??"880px",J=g.modalMaxHeight??"min(90vh, 800px)",le="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ae=Oe.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",et){let we=et.style;we.bottom=x,we.width=A??""}if(l&&h!=="fullscreen"){if(h==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=F,ae.maxWidth=le,ae.maxHeight=J,ae.height=J;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${x} + ${me})`,ae.top=X,ae.width=R,ae.maxWidth=le}},ys=()=>{if(!j())return;if(O()){let le=(o.launcher?.composerBar??{}).expandedSize??"anchored",me=Y?"expanded":"collapsed";Oe.dataset.state=me,Oe.dataset.expandedSize=le,et&&(et.dataset.state=me,et.dataset.expandedSize=le),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Gm(Y),ge.style.display=Y?"flex":"none",Ca(),Y?(qm(),Vm()):(Qd(),Zd()),vr();return}let l=Pt(o),g=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=h,R=x&&A&&P,X=tn(o).reveal;Y?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Gt&&(Gt.style.display="none")):(l?l&&(X==="overlay"||X==="push")&&!R?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.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"),pe.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"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=l?"none":"":Gt&&(Gt.style.display=l?"none":""))},ft=(l,g="user")=>{if(!j()||Y===l)return;let h=Y;Y=l,ys();let x=(()=>{let R=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,le=X.innerWidth<=J,me=Pt(o)&&F&&le,ae=O()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||F&&le&&P||me||ae})();if(Y&&x){if(!kn){let R=e.getRootNode(),X=R instanceof ShadowRoot?R.host:e.closest(".persona-host");X&&(kn=Rc(X,o.launcher?.zIndex??Kt))}Pn||(Pn=Ic(e.ownerDocument))}else Y||(kn?.(),kn=null,Pn?.(),Pn=null);Y&&(xs(),Jd()||(dn()==="follow"?po(!0):Kd()));let A={open:Y,source:g,timestamp:Date.now()};Y&&!h?d.emit("widget:opened",A):!Y&&h&&d.emit("widget:closed",A),d.emit("widget:state",{open:Y,launcherEnabled:P,voiceActive:Xe.active,streaming:$.isStreaming()})},Il=l=>{rt(l?"stop":"send"),K&&(K.disabled=l),Aa.buttons.forEach(g=>{g.disabled=l}),Q.dataset.personaComposerStreaming=l?"true":"false",Q.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Wl=()=>{Xe.active||fe&&fe.focus()};d.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Wl(),200)});let tp=()=>{v.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",I.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",fe.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=ie.querySelector("[data-persona-intro-card]");if(l){let h=o.copy?.showWelcomeCard!==!1;l.style.display=h?"":"none",h?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(Ae.textContent=o.copy?.sendButtonLabel??"Send"),fe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',fe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=u.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{k(g=>({...g,sessionId:l}))}});let Ko=null,Jm=()=>{Ko==null&&(Ko=setInterval(()=>{let l=Re.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ko),Ko=null;return}let g=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=ei(g-x))})},100))},Hl=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((X,F)=>Hl(X,g[F]));let h=l,x=g,A=Object.keys(h),R=Object.keys(x);return A.length===R.length&&A.every(X=>Object.prototype.hasOwnProperty.call(x,X)&&Hl(h[X],x[X]))},np=l=>{let{content:g,rawContent:h,llmContent:x,...A}=l;return A},Bl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!la(l),Xm=(l,g,h)=>{if(l.length!==g.length)return!1;let x=l[h.index],A=g[h.index];return!x||!A||x.id!==h.id||A.id!==h.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&Bl(x)&&Bl(A)&&Hl(np(x),np(A))},op=null,xr=null,Go=null,_n=null,Wa=l=>{op=l;let g,h;xr=null;for(let A=l.length-1;A>=0;A-=1){let R=l[A];if(!g&&R.role==="user"&&(g=R),!h&&R.role==="assistant"&&(h=R),!xr&&Bl(R)&&(xr={index:A,id:R.id}),g&&h&&xr)break}fs(Re,l,se),Tc(Re,yn.artifacts,{suppressTransition:vn}),Jm(),Al(l),po(!vn),Um(l),l.length===0&&(us(),cs=!0,Ma=!1,Ea=null,ka=!1),!Tl||Ta?(Tl=!0,ls=g?.id??null,Ml=h?.id??null):g&&g.id!==ls?(ls=g.id,_m(g.id)):h&&h.id!==Ml&&$m(),h&&(Ml=h.id),jm(l);let x=Xe.lastUserMessageId;g&&g.id!==x&&(Xe.lastUserMessageId=g.id,d.emit("user:message",g)),Xe.lastUserMessageWasVoice=!!g?.viaVoice,Pl(l),vr()},Dl=()=>{_n!==null&&(cancelAnimationFrame(_n),_n=null);let l=Go;Go=null,l&&Wa(l)},rp=()=>{_n!==null&&cancelAnimationFrame(_n),_n=null,Go=null},Ym=l=>{let g=Go??op;if(vn&&g&&xr&&Xm(g,l,xr)){Go=l,_n===null&&(_n=requestAnimationFrame(()=>{_n=null;let h=Go;Go=null,h&&Wa(h)}));return}if(l.length===0){rp(),Wa(l);return}Dl(),Wa(l)};$=new Or(o,{onMessagesChanged(l){Ym(l)},onStatusChanged(l){let g=o.statusIndicator??{};Lt(N,(x=>x==="idle"?g.idleText??Bt.idle:x==="connecting"?g.connectingText??Bt.connecting:x==="connected"?g.connectedText??Bt.connected:x==="error"?g.errorText??Bt.error:x==="paused"?g.pausedText??Bt.paused:x==="resuming"?g.resumingText??Bt.resuming:Bt[x])(l),g,l)},onStreamingChanged(l){l||($?.getMessages().length===0?rp():Dl()),vn=l,Il(l),$&&fs(Re,$.getMessages(),se),l||po(!0),rn(),Md(l?"Responding\u2026":"Response complete."),vr()},onVoiceStatusChanged(l){if(d.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":$n(),wr();break;case"processing":$n(),lh();break;case"speaking":$n(),ch();break;default:l==="idle"&&$.isBargeInActive()?($n(),wr(),K?.setAttribute("aria-label","End voice session")):(Xe.active=!1,$n(),Fn("system"),Cn());break}},onArtifactsState(l){yn=l,l.artifacts.length===0&&(gr=!1),Tc(Re,l.artifacts,{suppressTransition:vn}),Nn(),Pl()},onReconnect(l){let{executionId:g,lastEventId:h}=l.handle;l.phase==="paused"?d.emit("stream:paused",{executionId:g,after:h}):l.phase==="resuming"?d.emit("stream:resuming",{executionId:g,after:h,attempt:l.attempt??1}):d.emit("stream:resumed",{executionId:g,after:h})}}),pt.current=$,Ve.push(()=>$.cancel());let Ol=null;if($.onReadAloudChange((l,g)=>{Id=l,Wd=g,Hd();let h=l??Ol;l&&(Ol=l);let x=h?$.getMessages().find(A=>A.id===h)??null:null;d.emit("message:read-aloud",{messageId:h,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(Ol=null)}),Tl=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&$.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Ee||o.onSSEEvent)&&$.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),De?.processEvent(l,g),Ee?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let sp=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};b?b.then(l=>{if(l){if(l.metadata&&(u=rd(l.metadata),E.syncFromMetadata()),l.messages?.length){Ta=!0;try{$.hydrateMessages(l.messages)}finally{Ta=!1}}l.artifacts?.length&&$.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>sp()):sp();let ap=()=>{!O()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ft(!0,"auto")},Qm=(l,g)=>l?g?{refs:[...l.refs,...g.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([l.finalize(),g.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),hx(A)}}:l:g,Zm=()=>{let g=fe.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},bs=!1,eh=async l=>{let g=fe.value.trim(),h=Mt?.hasAttachments()??!1,x=g?await(nn?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){fe.value="",fe.style.height="auto",vs(),nn?.clear();return}let A=nn?.collectForSubmit()??null,R=x?.kind==="server"?x.mentions:null,X=Qm(A,R),F=x?.kind==="prompt"?x.sendText:g,J=!!A&&A.refs.length>0;if(!F&&!h&&!J&&!R)return;ap();let le;h&&(le=[],le.push(...Mt.getContentParts()),F&&le.push(So(F)));let me=x?.kind==="prompt"?void 0:Zm();fe.value="",fe.style.height="auto",vs(),$.sendMessage(F,{contentParts:le,mentions:X??void 0,contentSegments:me,viaVoice:l?.viaVoice}),h&&Mt.clearAttachments(),A&&nn?.clear()},Nl=async l=>{if(!bs){bs=!0;try{await eh(l)}finally{bs=!1}}},ip=l=>{if(l.preventDefault(),$.isStreaming()){$.cancel(),De?.reset(),Ne?.update();return}bs||Nl()},th=()=>o.features?.composerHistory!==!1,Fl={...kc},_l=!1,vs=()=>{Fl={...kc}},nh=()=>$.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),oh=l=>{if(!fe)return;_l=!0,fe.value=l,fe.dispatchEvent(new Event("input",{bubbles:!0})),_l=!1;let g=fe.value.length;fe.setSelectionRange(g,g)},rh=l=>{_l||(l.isComposing||nn?.handleInput(l.inputType??void 0),vs())},sh=l=>{if(fe&&!(!l.isComposing&&nn?.handleKeydown(l))){if(th()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=fe.selectionStart===0&&fe.selectionEnd===0,h=kf({direction:l.key==="ArrowUp"?"up":"down",history:nh(),currentValue:fe.value,atStart:g,state:Fl});if(Fl=h.state,h.handled){l.preventDefault(),h.value!==void 0&&oh(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}if(bs){l.preventDefault();return}vs(),l.preventDefault(),Ae.click()}}},lp=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(ge)&&($.cancel(),De?.reset(),Ne?.update(),vs(),l.preventDefault(),l.stopImmediatePropagation())},ah=async l=>{if(o.attachments?.enabled!==!0||!Mt)return;let g=ux(l.clipboardData);g.length!==0&&(l.preventDefault(),await Mt.handleFiles(g))},fn=null,Ln=!1,Cr=null,wt=null,cp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ha=(l="user")=>{if(Ln||$.isStreaming())return;let g=cp();if(!g)return;fn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;fn.continuous=!0,fn.interimResults=!0,fn.lang="en-US";let A=fe.value;fn.onresult=R=>{let X="",F="";for(let le=0;le<R.results.length;le++){let me=R.results[le],ae=me[0].transcript;me.isFinal?X+=ae+" ":F=ae}let J=A+X+F;fe.value=J,Cr&&clearTimeout(Cr),(X||F)&&(Cr=window.setTimeout(()=>{fe.value.trim()&&fn&&Ln&&(uo(),Nl({viaVoice:!0}))},x))},fn.onerror=R=>{R.error!=="no-speech"&&uo()},fn.onend=()=>{if(Ln){let R=fe.value.trim();R&&R!==A.trim()&&Nl({viaVoice:!0}),uo()}};try{if(fn.start(),Ln=!0,Xe.active=!0,l!=="system"&&(Xe.manuallyDeactivated=!1),Fn(l),Cn(),K){let R=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:R.iconName??"mic",iconSize:parseFloat(R.iconSize??o.sendButton?.size??"40")||24};let X=R.recordingBackgroundColor,F=R.recordingIconColor,J=R.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let le=K.querySelector("svg");le&&le.setAttribute("stroke",F)}J&&(K.style.borderColor=J),K.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Ln){if(Ln=!1,Cr&&(clearTimeout(Cr),Cr=null),fn){try{fn.stop()}catch{}fn=null}if(Xe.active=!1,Fn(l),Cn(),K){if(K.classList.remove("persona-voice-recording"),wt){K.style.backgroundColor=wt.backgroundColor,K.style.color=wt.color,K.style.borderColor=wt.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",wt.color||"currentColor"),wt=null}K.setAttribute("aria-label","Start voice recognition")}}},ih=(l,g)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",A=l?.provider?.type==="custom";if(!(h||x||A))return null;let X=m("div","persona-send-button-wrapper"),F=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button";let J=l?.tooltipText??"Start voice recognition";F.setAttribute("aria-label",J);let le=l?.iconName??"mic",me=g?.size??"40px",ae=l?.iconSize??me,we=parseFloat(ae)||24,Ke=l?.backgroundColor??g?.backgroundColor,gt=l?.iconColor??g?.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",gt?F.style.color=gt:F.style.color="var(--persona-text, #111827)";let sn=re(le,we,gt||"currentColor",1.5);sn?F.appendChild(sn):F.textContent="\u{1F3A4}",Ke?F.style.backgroundColor=Ke:F.style.backgroundColor="",l?.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l?.borderColor&&(F.style.borderColor=l.borderColor),l?.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l?.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),X.appendChild(F);let Et=l?.showTooltip??!1;return $t({anchor:F,trigger:X,text:()=>F.getAttribute("aria-label")??J,enabled:Et}),{micButton:F,micButtonWrapper:X}},$l=()=>{if(!K||wt)return;let l=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},jl=(l,g)=>{if(!K)return;let h=K.querySelector("svg");h&&h.remove();let x=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=re(l,x,g,1.5);A&&K.appendChild(A)},Ba=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},wr=()=>{if(!K)return;$l();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Ba(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=K.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},lh=()=>{if(!K)return;$l();let l=o.voiceRecognition??{},g=$.getVoiceInterruptionMode(),h=l.processingIconName??"loader",x=l.processingIconColor??wt?.color??"",A=l.processingBackgroundColor??wt?.backgroundColor??"",R=l.processingBorderColor??wt?.borderColor??"";Ba(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=A,K.style.borderColor=R;let X=x||"currentColor";K.style.color=X,jl(h,X),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},ch=()=>{if(!K)return;$l();let l=o.voiceRecognition??{},g=$.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=l.speakingIconName??h,A=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??wt?.color??"":wt?.color??""),R=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),X=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":wt?.borderColor??"");Ba(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=R,K.style.borderColor=X;let F=A||"currentColor";K.style.color=F,jl(x,F);let J=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",J),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},$n=()=>{K&&(Ba(),wt&&(K.style.backgroundColor=wt.backgroundColor??"",K.style.color=wt.color??"",K.style.borderColor=wt.borderColor??"",jl(wt.iconName,wt.color||"currentColor"),wt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Da=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=$.getVoiceStatus(),g=$.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,Cn(),Fn("user"),$n()});return}$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Xe.manuallyDeactivated=!$.isVoiceActive(),Cn(),Fn("user"),$.isVoiceActive()?wr():$n()});return}if(Ln){let l=fe.value.trim();Xe.manuallyDeactivated=!0,Cn(),uo("user"),l&&(fe.value="",fe.style.height="auto",$.sendMessage(l))}else Xe.manuallyDeactivated=!1,Cn(),Ha("user")};kd=Da,K&&(K.addEventListener("click",Da),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),$n()):uo("system"),K&&K.removeEventListener("click",Da)}));let dh=d.on("assistant:complete",()=>{$d&&(Xe.active||Xe.manuallyDeactivated||$d==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Fn("auto"),$.isVoiceActive()&&wr()}):Ha("auto"))},600))});Ve.push(dh);let ph=d.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Ve.push(ph);let dp=()=>{ft(!Y,"user")},Ft=null,Gt=null;if(P&&!O()){let{instance:l,element:g}=Oc({config:o,plugins:s,onToggle:dp});Ft=l,l||(Gt=g)}Ft?e.appendChild(Ft.element):Gt&&e.appendChild(Gt),ys(),Al(),tp(),Il($.isStreaming()),Jd()||(dn()==="follow"?po(!0):Kd()),Hm(),q&&(!P||O()?setTimeout(()=>Wl(),0):Y&&setTimeout(()=>Wl(),200));let xs=()=>{if(O()){fr(),ys();return}let l=Pt(o),g=o.launcher?.sidebarMode??!1,h=l||g||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640,X=x.innerWidth<=R,F=A&&X&&P;try{if(F){rs(),ss=xa();return}let J=!1;te&&(te=!1,rs(),J=!0);let le=xa();if(!J&&le!==ss&&(rs(),J=!0),ss=le,J&&Cl(),!P&&!l){pe.style.height="",pe.style.width="";return}if(!g&&!l){let ae=o?.launcher?.width??o?.launcherWidth??ln;pe.style.width=ae,pe.style.maxWidth=ae}if(va(),!h){let me=x.innerHeight,ae=64,we=o.launcher?.heightOffset??0,Ke=Math.max(200,me-ae),gt=Math.min(640,Ke),nt=Math.max(200,gt-we);pe.style.height=`${nt}px`}}finally{if(fr(),ys(),Y&&P){let le=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),me=o.launcher?.sidebarMode??!1,ae=o.launcher?.mobileFullscreen??!0,we=Pt(o)&&ae&&le,Ke=me||ae&&le&&P||we;if(Ke&&!Pn){let gt=e.getRootNode(),nt=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");nt&&!kn&&(kn=Rc(nt,o.launcher?.zIndex??Kt)),Pn=Ic(e.ownerDocument)}else Ke||(kn?.(),kn=null,Pn?.(),Pn=null)}}};xs();let pp=e.ownerDocument.defaultView??window;if(pp.addEventListener("resize",xs),Ve.push(()=>pp.removeEventListener("resize",xs)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{fr()});l.observe(Q),Ve.push(()=>l.disconnect())}pn=ie.scrollTop;let up=Hn(ie),fp=()=>{let l=ie.scrollTop,g=Hn(ie),h=g<up;if(up=g,!no()){pn=l,rn();return}let{action:x,nextLastScrollTop:A}=Ri({following:on.isFollowing(),currentScrollTop:l,lastScrollTop:pn,nearBottom:Io(ie,Pa),userScrollThreshold:Im,isAutoScrolling:un||Sa||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=A,x==="resume"){Ra()||co();return}x==="pause"&&ps()};if(ie.addEventListener("scroll",fp,{passive:!0}),Ve.push(()=>ie.removeEventListener("scroll",fp)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Fm(),Jl(Re)});l.observe(Re),l.observe(ie),Ve.push(()=>l.disconnect())}let gp=()=>{no()&&on.isFollowing()&&Ra()&&ps()},mp=ie.ownerDocument;mp.addEventListener("selectionchange",gp),Ve.push(()=>{mp.removeEventListener("selectionchange",gp)});let uh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),hp=l=>{uh.has(l.key)&&(qo(),Ad()&&no()&&on.isFollowing()&&ps())},yp=l=>{l.target?.closest("a, button, [tabindex], input, textarea, select")&&(qo(),Ad()&&no()&&on.isFollowing()&&ps())};ie.addEventListener("keydown",hp),ie.addEventListener("focusin",yp),Ve.push(()=>{ie.removeEventListener("keydown",hp),ie.removeEventListener("focusin",yp)});let bp=l=>{if(l.deltaY!==0&&qo(),!no())return;let g=Ii({following:on.isFollowing(),deltaY:l.deltaY,nearBottom:Io(ie,Pa),resumeWhenNearBottom:!0});g==="pause"?ps():g==="resume"&&!Ra()&&co()};ie.addEventListener("wheel",bp,{passive:!0}),ie.addEventListener("touchmove",qo,{passive:!0}),ie.addEventListener("pointerdown",qo,{passive:!0}),Ve.push(()=>{ie.removeEventListener("touchmove",qo),ie.removeEventListener("pointerdown",qo)}),Ve.push(()=>ie.removeEventListener("wheel",bp)),Rt.addEventListener("click",()=>{us(),ie.scrollTop=ie.scrollHeight,pn=ie.scrollTop,co(),po(!0),rn()}),Ve.push(()=>Rt.remove()),Ve.push(()=>{zd(),us()});let vp=()=>{M&&($o&&(M.removeEventListener("click",$o),$o=null),j()?(M.style.display="",$o=()=>{ft(!1,"user")},M.addEventListener("click",$o)):M.style.display="none")};vp(),(()=>{let{clearChatButton:l}=Ie;l&&l.addEventListener("click",()=>{$.clearMessages(),jo.clear(),co(),xo(Ie.composerOverlay);try{localStorage.removeItem(Zr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Zr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),c?.clear&&kl(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Ee?.clear(),De?.reset(),Ne?.update()})})(),T&&T.addEventListener("submit",ip);let xp=[["keydown",sh],["input",rh],["paste",ah],["focus",Em]],Cp=l=>{if(l)for(let[g,h]of xp)l.addEventListener(g,h)},wp=l=>{if(l)for(let[g,h]of xp)l.removeEventListener(g,h)};Cp(fe),nn?.onComposerSwap((l,g)=>{wp(g),fe=l,Cp(l)});let Ap=e.ownerDocument??document;Ap.addEventListener("keydown",lp,!0);let Sp="persona-attachment-drop-active",Cs=0,Ul=()=>{Cs=0,ge.classList.remove(Sp)},Ar=()=>o.attachments?.enabled===!0&&Mt!==null,Tp=l=>{!sl(l.dataTransfer)||!Ar()||(Cs++,Cs===1&&ge.classList.add(Sp))},Mp=l=>{!sl(l.dataTransfer)||!Ar()||(Cs--,Cs<=0&&Ul())},Ep=l=>{!sl(l.dataTransfer)||!Ar()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},kp=l=>{if(!sl(l.dataTransfer)||!Ar())return;l.preventDefault(),l.stopPropagation(),Ul();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&Mt.handleFiles(g)},fo=!0;ge.addEventListener("dragenter",Tp,fo),ge.addEventListener("dragleave",Mp,fo),e.addEventListener("dragover",Ep,fo),e.addEventListener("drop",kp,fo);let Oa=e.ownerDocument,Pp=l=>{Ar()&&l.preventDefault()},Lp=l=>{Ar()&&l.preventDefault()};Oa.addEventListener("dragover",Pp),Oa.addEventListener("drop",Lp),Ve.push(()=>{T&&T.removeEventListener("submit",ip),wp(fe),Ap.removeEventListener("keydown",lp,!0),nn?.destroy()}),Ve.push(()=>{ge.removeEventListener("dragenter",Tp,fo),ge.removeEventListener("dragleave",Mp,fo),e.removeEventListener("dragover",Ep,fo),e.removeEventListener("drop",kp,fo),Oa.removeEventListener("dragover",Pp),Oa.removeEventListener("drop",Lp),Ul()}),Ve.push(()=>{$.cancel()}),Ft?Ve.push(()=>{Ft?.destroy()}):Gt&&Ve.push(()=>{Gt?.remove()});let It={update(l){let g=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,R=o.loadingIndicator,X=o.iterationDisplay,F=o.features?.showReasoning,J=o.features?.showToolCalls,le=o.features?.toolCallDisplay,me=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type;o=Qi({...o,features:r},l),r=o.features,o=ra(o),Ca(),or(e,o),na(e,o),oa(e,o),Nn(),o.colorScheme!==A&&_d();let we=sa.getForInstance(o.plugins);s.length=0,s.push(...we),P=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,he=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,Z=o.features?.scrollToBottom??{};let Ke=dn();ue=o.features?.scrollBehavior??{},Ke!==dn()&&(us(),co()),Ed(),rn();let gt=de;if(de=o.features?.showEventStreamToggle??!1,de&&!gt){if(Ee||(Se=new ea(ye),Ee=new Zs(lt,Se),De=De??new ta,Se.open().then(()=>Ee?.restore()).catch(()=>{}),$.setSSEEventCallback((oe,Je)=>{o.onSSEEvent?.(oe,Je),De?.processEvent(oe,Je),Ee.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:oe,timestamp:Date.now(),payload:JSON.stringify(Je)})})),!tt&&U){let oe=o.features?.eventStream?.classNames,Je="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(oe?.toggleButton?" "+oe.toggleButton:"");tt=m("button",Je),tt.style.width="28px",tt.style.height="28px",tt.style.color=Xt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let bt=re("activity","18px","currentColor",1.5);bt&&tt.appendChild(bt);let ot=Ie.clearChatButtonWrapper,at=Ie.closeButtonWrapper,qt=ot||at;qt&&qt.parentNode===U?U.insertBefore(tt,qt):U.appendChild(tt),tt.addEventListener("click",()=>{qe?ns():yl()})}}else!de&>&&(ns(),tt&&(tt.remove(),tt=null),Ee?.clear(),Se?.destroy(),Ee=null,Se=null,De?.reset(),De=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Gt&&(Gt.remove(),Gt=null),o.launcher?.enabled!==!1&&!Ft&&!Gt){let{instance:oe,element:Je}=Oc({config:o,plugins:s,onToggle:dp});Ft=oe,oe||(Gt=Je),e.appendChild(Je)}Ft&&Ft.update(o),G&&o.launcher?.title!==void 0&&(G.textContent=o.launcher.title),D&&o.launcher?.subtitle!==void 0&&(D.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==V&&U){let oe=nt?zr(o,nt,{showClose:j(),onClose:()=>ft(!1,"user")}):Zn({config:o,showClose:j(),onClose:()=>ft(!1,"user")});Tt.replaceHeader(oe),U=Tt.header.element,W=Tt.header.iconHolder,G=Tt.header.headerTitle,D=Tt.header.headerSubtitle,M=Tt.header.closeButton,V=nt?.layout}else if(nt){if(W&&(W.style.display=nt.showIcon===!1?"none":""),G&&(G.style.display=nt.showTitle===!1?"none":""),D&&(D.style.display=nt.showSubtitle===!1?"none":""),M){let oe=j()&&nt.showCloseButton!==!1;M.style.display=oe?"":"none"}if(Ie.clearChatButtonWrapper){let oe=nt.showClearChat;if(oe!==void 0){Ie.clearChatButtonWrapper.style.display=oe?"":"none";let{closeButtonWrapper:Je}=Ie;Je&&!Je.classList.contains("persona-absolute")&&(oe?Je.classList.remove("persona-ml-auto"):Je.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;U&&(U.style.display=Et?"":"none");let Wt=o.layout?.showFooter!==!1;Q&&(Q.style.display=Wt?"":"none"),fr(),rn(),P!==z?P?ft(_,"auto"):(Y=!0,ys()):_!==w&&ft(_,"auto"),w=_,z=P,xs(),vp();let $e=JSON.stringify(o.toolCall)!==JSON.stringify(g),Te=JSON.stringify(o.messageActions)!==JSON.stringify(h),St=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),mt=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,Nt=o.iterationDisplay!==X,ht=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(me);($e||Te||St||mt||Nt||ht)&&$&&(Sl++,fs(Re,$.getMessages(),se));let Ht=o.features?.streamAnimation?.type;if(Ht!==ae&&Ht&&Ht!=="none"){let oe=Ur(Ht,o.features?.streamAnimation?.plugins);oe&&Di(oe,e)}let Pe=o.launcher??{},je=Pe.headerIconHidden??!1,jt=o.layout?.header?.showIcon,Ut=je||jt===!1,At=Pe.headerIconName,ut=Pe.headerIconSize??"48px";if(W){let oe=ge.querySelector(".persona-border-b-persona-divider"),Je=oe?.querySelector(".persona-flex-col");if(Ut)W.style.display="none",oe&&Je&&!oe.contains(Je)&&oe.insertBefore(Je,oe.firstChild);else{if(W.style.display="",W.style.height=ut,W.style.width=ut,oe&&Je&&(oe.contains(W)?W.nextSibling!==Je&&(W.remove(),oe.insertBefore(W,Je)):oe.insertBefore(W,Je)),At){let ot=parseFloat(ut)||24,at=re(At,ot*.6,"currentColor",1);at?W.replaceChildren(at):W.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let ot=W.querySelector("img");if(ot)ot.src=Pe.iconUrl,ot.style.height=ut,ot.style.width=ut;else{let at=document.createElement("img");at.src=Pe.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=ut,at.style.width=ut,W.replaceChildren(at)}}else{let ot=W.querySelector("svg"),at=W.querySelector("img");(ot||at)&&W.replaceChildren(),W.textContent=Pe.agentIconText??"\u{1F4AC}"}let bt=W.querySelector("img");bt&&(bt.style.height=ut,bt.style.width=ut)}}let yt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(G&&(G.style.display=yt===!1?"none":""),D&&(D.style.display=Ze===!1?"none":""),M){let oe=j()&&o.layout?.header?.showCloseButton!==!1;M.style.display=oe?"":"none";let Je=Pe.closeButtonSize??"32px",bt=Pe.closeButtonPlacement??"inline";M.style.height=Je,M.style.width=Je;let{closeButtonWrapper:ot}=Ie,at=bt==="top-right",qt=ot?.classList.contains("persona-absolute");if(ot&&at!==qt)if(ot.remove(),at)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(ot);else{let mo=Pe.clearChat?.placement??"inline",Ss=Pe.clearChat?.enabled??!0;ot.className=Ss&&mo==="inline"?"":"persona-ml-auto";let Rp=ge.querySelector(".persona-border-b-persona-divider");Rp&&Rp.appendChild(ot)}if(M.style.color=Pe.closeButtonColor||Xt.actionIconColor,Pe.closeButtonBackgroundColor?(M.style.backgroundColor=Pe.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let mo=Pe.closeButtonBorderWidth||"0px",Ss=Pe.closeButtonBorderColor||"transparent";M.style.border=`${mo} solid ${Ss}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(M.style.borderRadius=Pe.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(M.style.paddingLeft=Pe.closeButtonPaddingX,M.style.paddingRight=Pe.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),Pe.closeButtonPaddingY?(M.style.paddingTop=Pe.closeButtonPaddingY,M.style.paddingBottom=Pe.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom="");let an=Pe.closeButtonIconName??"x",wn=Pe.closeButtonIconText??"\xD7";M.innerHTML="";let _t=re(an,"28px","currentColor",1);_t?(_t.style.display="block",M.appendChild(_t)):M.textContent=wn;let Vt=Pe.closeButtonTooltipText??"Close chat",Un=Pe.closeButtonShowTooltip??!0;M.setAttribute("aria-label",Vt),ot&&$t({anchor:M,trigger:ot,text:()=>M?.getAttribute("aria-label")??Vt,enabled:Un})}let{clearChatButton:He,clearChatButtonWrapper:vt}=Ie;if(He){let oe=Pe.clearChat??{},Je=oe.enabled??!0,bt=o.layout?.header?.showClearChat,ot=bt!==void 0?bt:Je,at=oe.placement??"inline";if(vt){vt.style.display=ot?"":"none";let{closeButtonWrapper:qt}=Ie;!O()&&qt&&!qt.classList.contains("persona-absolute")&&(ot?qt.classList.remove("persona-ml-auto"):qt.classList.add("persona-ml-auto"));let an=at==="top-right",wn=vt.classList.contains("persona-absolute");if(!O()&&an!==wn&&ot){if(vt.remove(),an)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",ge.style.position="relative",ge.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Vt=ge.querySelector(".persona-border-b-persona-divider"),Un=Ie.closeButtonWrapper;Vt&&Un&&Un.parentElement===Vt?Vt.insertBefore(vt,Un):Vt&&Vt.appendChild(vt)}let _t=Ie.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(an?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(ot){if(!O()){let mo=oe.size??"32px";He.style.height=mo,He.style.width=mo}let qt=oe.iconName??"refresh-cw",an=oe.iconColor??"";He.style.color=an||Xt.actionIconColor,He.innerHTML="";let wn=O()?"14px":"20px",_t=re(qt,wn,"currentColor",1);if(_t&&(_t.style.display="block",He.appendChild(_t)),oe.backgroundColor?(He.style.backgroundColor=oe.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),oe.borderWidth||oe.borderColor){let mo=oe.borderWidth||"0px",Ss=oe.borderColor||"transparent";He.style.border=`${mo} solid ${Ss}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");oe.borderRadius?(He.style.borderRadius=oe.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),oe.paddingX?(He.style.paddingLeft=oe.paddingX,He.style.paddingRight=oe.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),oe.paddingY?(He.style.paddingTop=oe.paddingY,He.style.paddingBottom=oe.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Vt=oe.tooltipText??"Clear chat",Un=oe.showTooltip??!0;He.setAttribute("aria-label",Vt),vt&&$t({anchor:He,trigger:vt,text:()=>He?.getAttribute("aria-label")??Vt,enabled:Un})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[aa],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ur.message,ur.messageAndClick];E=ia({parsers:zt,handlers:mn,getSessionMetadata:C,updateSessionMetadata:k,emit:d.emit,documentRef:typeof document<"u"?document:null}),se=Hg(o,E,Be),$.updateConfig(o),fs(Re,$.getMessages(),se),Al(),tp(),Il($.isStreaming());let ws=o.voiceRecognition?.enabled===!0,Na=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(ws&&(Na||kt))if(!K||!Ue){let oe=ih(o.voiceRecognition,o.sendButton);oe&&(K=oe.micButton,Ue=oe.micButtonWrapper,We.insertBefore(Ue,ne),K.addEventListener("click",Da),K.disabled=$.isStreaming())}else{let oe=o.voiceRecognition??{},Je=o.sendButton??{},bt=oe.iconName??"mic",ot=Je.size??"40px",at=oe.iconSize??ot,qt=parseFloat(at)||24;K.style.width=at,K.style.height=at,K.style.minWidth=at,K.style.minHeight=at;let an=oe.iconColor??Je.textColor;K.innerHTML="";let wn=re(bt,qt,an||"currentColor",1.5);wn?K.appendChild(wn):K.textContent="\u{1F3A4}";let _t=oe.backgroundColor??Je.backgroundColor;_t?K.style.backgroundColor=_t:K.style.backgroundColor="",an?K.style.color=an:K.style.color="var(--persona-text, #111827)",oe.borderWidth?(K.style.borderWidth=oe.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),oe.borderColor?K.style.borderColor=oe.borderColor:K.style.borderColor="",oe.paddingX?(K.style.paddingLeft=oe.paddingX,K.style.paddingRight=oe.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),oe.paddingY?(K.style.paddingTop=oe.paddingY,K.style.paddingBottom=oe.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Vt=oe.tooltipText??"Start voice recognition",Un=oe.showTooltip??!1;K.setAttribute("aria-label",Vt),Ue&&$t({anchor:K,trigger:Ue,text:()=>K?.getAttribute("aria-label")??Vt,enabled:Un}),Ue.style.display="",K.disabled=$.isStreaming()}else K&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():Ln&&uo());if(o.attachments?.enabled===!0){if(!ze||!Ce){let oe=o.attachments??{},bt=(o.sendButton??{}).size??"40px";Dt||(Dt=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Dt.style.display="none",T.insertBefore(Dt,fe)),_e||(_e=document.createElement("input"),_e.type="file",_e.accept=(oe.allowedTypes??Xn).join(","),_e.multiple=(oe.maxFiles??4)>1,_e.style.display="none",_e.setAttribute("aria-label","Attach files"),T.insertBefore(_e,fe)),ze=m("div","persona-send-button-wrapper"),Ce=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ce.type="button",Ce.setAttribute("aria-label",oe.buttonTooltipText??"Attach file");let ot=oe.buttonIconName??"paperclip",at=bt,qt=parseFloat(at)||40,an=Math.round(qt*.6);Ce.style.width=at,Ce.style.height=at,Ce.style.minWidth=at,Ce.style.minHeight=at,Ce.style.fontSize="18px",Ce.style.lineHeight="1";let wn=re(ot,an,"currentColor",1.5);wn?Ce.appendChild(wn):Ce.textContent="\u{1F4CE}",Ce.addEventListener("click",Vt=>{Vt.preventDefault(),_e?.click()}),ze.appendChild(Ce);let _t=oe.buttonTooltipText??"Attach file";$t({anchor:Ce,trigger:ze,text:()=>Ce?.getAttribute("aria-label")??_t}),Ye?Ye.append(ze):T.appendChild(ze),!Mt&&_e&&Dt&&(Mt=nr.fromConfig(oe),Mt.setPreviewsContainer(Dt),_e.addEventListener("change",async()=>{Mt&&_e?.files&&(await Mt.handleFileSelect(_e.files),_e.value="")}))}else{ze.style.display="";let oe=o.attachments??{};_e&&(_e.accept=(oe.allowedTypes??Xn).join(","),_e.multiple=(oe.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:oe.allowedTypes,maxFileSize:oe.maxFileSize,maxFiles:oe.maxFiles})}if(ge.querySelector(".persona-attachment-drop-overlay")?.remove(),ge.appendChild(Bg(o.attachments?.dropOverlay)),Ce){let oe=o.attachments??{},Je=oe.buttonTooltipText??"Attach file";Ce.setAttribute("aria-label",Je),Ce.textContent="";let bt=parseFloat(o.sendButton?.size??"40px")||40,ot=re(oe.buttonIconName??"paperclip",Math.round(bt*.6),"currentColor",1.5);ot?Ce.appendChild(ot):Ce.textContent="\u{1F4CE}",ze&&$t({anchor:Ce,trigger:ze,text:()=>Ce?.getAttribute("aria-label")??Je})}}else ze&&(ze.style.display="none"),Mt&&Mt.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let Ot=o.sendButton??{},As=Ot.useIcon??!1,_a=Ot.iconText??"\u2191",Sr=Ot.iconName,$a=Ot.tooltipText??"Send message",zl=Ot.showTooltip??!1,Jo=Ot.size??"40px",jn=Ot.backgroundColor,Xo=Ot.textColor;if(As){if(Ae.style.width=Jo,Ae.style.height=Jo,Ae.style.minWidth=Jo,Ae.style.minHeight=Jo,Ae.style.fontSize="18px",Ae.style.lineHeight="1",Xo?Ae.style.color=Xo:Ae.style.color="var(--persona-button-primary-fg, #ffffff)",!$.isStreaming())if(Ae.innerHTML="",Sr){let oe=parseFloat(Jo)||24,Je=Xo?.trim()||"currentColor",bt=re(Sr,oe,Je,2);bt?Ae.appendChild(bt):Ae.textContent=_a}else Ae.textContent=_a;Ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",jn?(Ae.style.backgroundColor=jn,Ae.classList.remove("persona-bg-persona-primary")):(Ae.style.backgroundColor="",Ae.classList.add("persona-bg-persona-primary"))}else Ae.textContent=o.copy?.sendButtonLabel??"Send",Ae.style.width="",Ae.style.height="",Ae.style.minWidth="",Ae.style.minHeight="",Ae.style.fontSize="",Ae.style.lineHeight="",Ae.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",jn?(Ae.style.backgroundColor=jn,Ae.classList.remove("persona-bg-persona-accent")):Ae.classList.add("persona-bg-persona-accent"),Xo?Ae.style.color=Xo:Ae.classList.add("persona-text-white");Ot.borderWidth?(Ae.style.borderWidth=Ot.borderWidth,Ae.style.borderStyle="solid"):(Ae.style.borderWidth="",Ae.style.borderStyle=""),Ot.borderColor?Ae.style.borderColor=Ot.borderColor:Ae.style.borderColor="",Ot.paddingX?(Ae.style.paddingLeft=Ot.paddingX,Ae.style.paddingRight=Ot.paddingX):(Ae.style.paddingLeft="",Ae.style.paddingRight=""),Ot.paddingY?(Ae.style.paddingTop=Ot.paddingY,Ae.style.paddingBottom=Ot.paddingY):(Ae.style.paddingTop="",Ae.style.paddingBottom=""),$.isStreaming()||Ae.setAttribute("aria-label",$a),ne&&$t({anchor:Ae,trigger:ne,text:()=>Ae.getAttribute("aria-label")??$a,enabled:zl});let ja=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ja?(Re.style.maxWidth=ja,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",T&&(T.style.maxWidth=ja,T.style.marginLeft="auto",T.style.marginRight="auto"),ct&&(ct.style.maxWidth=ja,ct.style.marginLeft="auto",ct.style.marginRight="auto")):(Re.style.maxWidth="",Re.style.marginLeft="",Re.style.marginRight="",Re.style.width="",T&&(T.style.maxWidth="",T.style.marginLeft="",T.style.marginRight=""),ct&&(ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight=""));let go=o.statusIndicator??{},fh=go.visible??!0;if(N.style.display=fh?"":"none",$){let oe=$.getStatus();Lt(N,(bt=>bt==="idle"?go.idleText??Bt.idle:bt==="connecting"?go.connectingText??Bt.connecting:bt==="connected"?go.connectedText??Bt.connected:bt==="error"?go.errorText??Bt.error:Bt[bt])(oe),go,oe)}N.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gh=go.align==="left"?"persona-text-left":go.align==="center"?"persona-text-center":"persona-text-right";N.classList.add(gh)},open(){j()&&ft(!0,"api")},close(){j()&&ft(!1,"api")},toggle(){j()&&ft(!Y,"api")},reconnect(){$.reconnectNow()},clearChat(){On=!1,$.clearMessages(),jo.clear(),co();try{localStorage.removeItem(Zr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Zr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),c?.clear&&kl(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Ee?.clear(),De?.reset(),Ne?.update()},setMessage(l){return!fe||$.isStreaming()?!1:(!Y&&j()&&ft(!0,"system"),fe.value=l,fe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let g=l?.trim()||fe.value.trim();return g?(!Y&&j()&&ft(!0,"system"),fe.value="",fe.style.height="auto",$.sendMessage(g),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!Y&&j()&&ft(!0,"system"),Xe.manuallyDeactivated=!1,Cn(),$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Fn("user"),$.isVoiceActive()&&wr()})),!0):Ln?!0:cp()?(!Y&&j()&&ft(!0,"system"),Xe.manuallyDeactivated=!1,Cn(),Ha("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,Cn(),Fn("user"),$n()}),!0):!1:Ln?(Xe.manuallyDeactivated=!0,Cn(),uo("user"),!0):!1},injectMessage(l){return!Y&&j()&&ft(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!Y&&j()&&ft(!0,"system");let g=$.injectAssistantMessage(l);return be&&(be=!1,ve&&(clearTimeout(ve),ve=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(l){return!Y&&j()&&ft(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!Y&&j()&&ft(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!Y&&j()&&ft(!0,"system"),$.injectMessageBatch(l)},injectComponentDirective(l){return!Y&&j()&&ft(!0,"system"),$.injectComponentDirective(l)},injectTestMessage(l){!Y&&j()&&ft(!0,"system"),$.injectTestEvent(l)},async connectStream(l,g){return $.connectStream(l,g)},__pushEventStreamEvent(l){Ee&&(De?.processEvent(l.type,l.payload),Ee.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!de||!Ee||yl()},hideEventStream(){qe&&ns()},isEventStreamVisible(){return qe},showArtifacts(){Yt(o)&&(On=!1,gr=!0,Nn(),Qe?.setMobileOpen(!0))},hideArtifacts(){Yt(o)&&(On=!0,Nn())},upsertArtifact(l){return Yt(o)?(In(o.features?.artifacts,{artifactType:l.artifactType,...l.artifactType==="markdown"&&l.file?{file:l.file}:{},...l.presentation?{presentation:l.presentation}:{}})==="panel"&&(On=!1,gr=!0),$.upsertArtifact(l)):null},selectArtifact(l){Yt(o)&&$.selectArtifact(l)},clearArtifacts(){Yt(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return P&&!Y&&!O()||!fe?!1:(fe.focus(),!0)},async resolveApproval(l,g,h){let A=$.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===l);if(!A?.approval)throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){$.resolveWebMcpApproval(A.id,g);return}return $.resolveApproval(A.approval,g,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(l){k(l)},on(l,g){return d.on(l,g)},off(l,g){d.off(l,g)},isOpen(){return j()&&Y},isVoiceActive(){return Xe.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:j()&&Y,launcherEnabled:P,voiceActive:Xe.active,streaming:$.isStreaming()}},showCSATFeedback(l){!Y&&j()&&ft(!0,"system");let g=Re.querySelector(".persona-feedback-container");g&&g.remove();let h=ol({onSubmit:async(x,A)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});Re.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!Y&&j()&&ft(!0,"system");let g=Re.querySelector(".persona-feedback-container");g&&g.remove();let h=rl({onSubmit:async(x,A)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});Re.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return $.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return $.submitNPSFeedback(l,g)},destroy(){Dl(),Ko!=null&&(clearInterval(Ko),Ko=null),Ve.forEach(l=>l()),Oe.remove(),et?.remove(),Ft?.destroy(),Gt?.remove(),$o&&M.removeEventListener("click",$o)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:h=>h?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ve.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",g),Ve.push(()=>{window.removeEventListener("persona:focusInput",g)}),de){let F=le=>{let me=le.detail;(!me?.instanceId||me.instanceId===l)&&It.showEventStream()},J=le=>{let me=le.detail;(!me?.instanceId||me.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",J),Ve.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",J)})}let h=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&It.showArtifacts()},x=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&It.hideArtifacts()},A=F=>{let J=F.detail;J?.instanceId&&J.instanceId!==l||J?.artifact&&It.upsertArtifact(J.artifact)},R=F=>{let J=F.detail;J?.instanceId&&J.instanceId!==l||typeof J?.id=="string"&&It.selectArtifact(J.id)},X=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",X),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",X)})}let gn=fx(o.persistState);if(gn&&j()){let l=gx(gn.storage),g=`${gn.keyPrefix}widget-open`,h=`${gn.keyPrefix}widget-voice`,x=`${gn.keyPrefix}widget-voice-mode`;if(l){let A=gn.persist?.openState&&l.getItem(g)==="true",R=gn.persist?.voiceState&&l.getItem(h)==="true",X=gn.persist?.voiceState&&l.getItem(x)==="true";if(A&&setTimeout(()=>{It.open(),setTimeout(()=>{if(R||X)It.startVoiceRecognition();else if(gn.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),gn.persist?.openState&&(d.on("widget:opened",()=>{l.setItem(g,"true")}),d.on("widget:closed",()=>{l.setItem(g,"false")})),gn.persist?.voiceState&&(d.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),d.on("user:message",F=>{l.setItem(x,F.viaVoice?"true":"false")})),gn.clearOnChatClear){let F=()=>{l.removeItem(g),l.removeItem(h),l.removeItem(x)},J=()=>F();window.addEventListener("persona:clear-chat",J),Ve.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(f&&j()&&setTimeout(()=>{It.open()},0),vr(),!Rm){let l=Er(()=>{$&&(Sl++,jo.clear(),fs(Re,$.getMessages(),se))});Ve.push(l)}return It};var Dg=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},yx=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},bx=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},vx=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Og=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},ld=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=""},Ng=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ld(e)},sd=e=>{e.style.transition=""},ad=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=""},id=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},il=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},xx=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Cx=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},wx=e=>{let t=Eo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Jt(t,r)??r;return{inset:o(n?.inset,yi),canvasBackground:o(n?.canvasBackground,bi)}},Fg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Ax=(e,t,n,o,r,s,a,i)=>{let d=tn(s),p=d.reveal==="push",c=i!=null,u=i?.inset??"",b=i?.canvasBackground??"";xx(e,t,n,o,p),Cx(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,k=f!=null?f.innerWidth<=C:!1;if(y&&k&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ad(t),sd(o),Ng(o),id(n),il(r,o),Fg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Kt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(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"),Ng(o),yx(o,d.maxHeight),Fg(o,c&&a,u,b),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ad(t),sd(o),id(n),il(r,o);let H=d.animate?"transform 180ms ease":"none",E=d.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":E;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=P,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",sd(o),ld(o),il(r,o);let H=Dg(d.width,e.clientWidth),E=Math.max(0,e.clientWidth),P=d.animate?"margin-left 180ms ease":"none",_=d.side==="right"?a?-H:0:a?0:-H;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=`${E+H}px`,t.style.transition=P,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ad(t),ld(o),id(n),il(r,o);let H=d.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?d.width:"0px",P=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",_=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",bx(o,d.maxHeight),o.style.overflow=H||_?"hidden":"visible",o.style.transition=P,H){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let q=c?`calc(${Dg(d.width,e.clientWidth)}px - (2 * ${u}))`:d.width;r.style.width=q,r.style.minWidth=q,r.style.maxWidth=q,r.style.boxSizing="border-box"}}},Sx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Og(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Og(n,o)},destroy(){n.remove()}}},Tx=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",p.appendChild(c),o.insertBefore(a,e),d.appendChild(e);let b=null,f=()=>{b?.disconnect(),b=null},y=null,C=()=>{y=t?.launcher?.detachedPanel===!0?wx(t):null};C();let k=()=>{Ax(a,i,d,p,c,t,u,y)},L=null,H=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=Fr(()=>{C(),k()}))},E=()=>{f(),tn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{k()}),b.observe(a)))},P=!1,_=()=>{k(),E(),u&&!P&&a.dataset.personaDockMobileFullscreen!=="true"&&(P=!0,vx(a,tn(t)))},q=a.ownerDocument.defaultView,w=()=>{_()};return q?.addEventListener("resize",w),tn(t).reveal==="push"?(i.appendChild(d),i.appendChild(p),a.appendChild(i)):(a.appendChild(d),a.appendChild(p)),_(),H(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let V=z.launcherEnabled?z.open:!0;u!==V&&(u=V,_())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),_(),H()},destroy(){q?.removeEventListener("resize",w),L?.(),L=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},ca=(e,t)=>Pt(t)?Tx(e,t):Sx(e,t);var Mx=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},_g=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},cd=e=>{let t=Mx(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=ca(t,r),a,i=[],d=(k,L)=>{let E=!(L?.launcher?.enabled??!0)||Pt(L),P=o.createElement("div");if(P.setAttribute("data-persona-root","true"),E&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0",P.style.minWidth="0"),n){let _=k.attachShadow({mode:"open"});_.appendChild(P),_g(_,o)}else k.appendChild(P),_g(k,o);return t.id&&P.setAttribute("data-persona-instance",t.id),P},p=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(k=>k()),i=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},u=()=>{let k=d(s.host,r);a=al(k,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(k=>k()),i=[],a.destroy()};u(),e.onChatReady?.();let f=k=>{b(),s.destroy(),s=ca(t,k),r=k,u()},y={update(k){let L=Qi(r??{},k),H=Pt(r),E=Pt(L),P=Ho(r),_=Ho(L);if(H!==E||P!==_){f(L);return}r=L,s.updateConfig(r),a.update(k),p()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(y,{get(k,L,H){if(L==="host")return s.host;if(L in k)return Reflect.get(k,L,H);let E=a[L];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function Ex(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function kx(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:Ex(o,n)?2:3}function $g(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function ll(e,t){let n=t.trim();if(!n)return[...e].sort($g);let o=[];for(let r of e){let s=kx(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:$g(r.item,s.item)),o.map(r=>r.item)}function Px(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function jg(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>ll(e.items,t),resolve:e.resolve}}function Ug(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>ll(t,Px(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var Gg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Lx=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"]),dd=/\b(product|card|item|listing|result)\b/i,ud=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ix=3e3,Wx=100;function Jg(e){let t=typeof e.className=="string"?e.className:"";if(dd.test(t)||e.id&&dd.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&dd.test(o.value))return!0}return!1}function Xg(e){return ud.test((e.textContent??"").trim())}function Yg(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Hx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function zg(e){let t=e.match(ud);return t?t[0]:null}function qg(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Bx(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var Dx="commerce-card",Ox="result-card";function Vg(e){return!Jg(e)||!Xg(e)||!Yg(e)&&!Hx(e)?0:5200}function Kg(e){return!Jg(e)||Xg(e)||!Yg(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var fd=[{id:Dx,scoreElement(e){return Vg(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||ud.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Vg(e)===0)return null;let{title:n,href:o}=qg(e),r=zg((e.textContent??"").trim())??zg(t.text)??"",s=Bx(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
143
|
-
`)}},{id:
|
|
144
|
-
`)}}];function
|
|
141
|
+
${wt?"background: transparent !important;":""}
|
|
142
|
+
`}if(!x&&!l){let kt="max-height: -moz-available !important; max-height: stretch !important;",tn=g?"":"padding-top: 1.25em !important;",za=g?"":`z-index: ${o.launcher?.zIndex??Kt} !important;`;Oe.style.cssText+=kt+tn+za}yn()};Ea(),lr(e,o),ca(e,o),da(e,o),cs=()=>{Ea(),lr(e,o),ca(e,o),da(e,o),xa?e.style.setProperty("--persona-artifact-welded-outer-radius",xa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let je=[];je.push(()=>{document.removeEventListener("keydown",zd)}),je.push(()=>{as!==null&&clearTimeout(as)});let Rn=null,In=null;je.push(()=>{Rn?.(),Rn=null,In?.(),In=null}),ls&&je.push(()=>{ls?.disconnect(),ls=null}),je.push(()=>{us?.(),us=null,Pl(),xt&&(xt.remove(),xt=null),Je?.element.style.removeProperty("width"),Je?.element.style.removeProperty("maxWidth")}),de&&je.push(()=>{ke!==null&&(cancelAnimationFrame(ke),ke=null),Fe?.destroy(),Fe=null,Se?.destroy(),Se=null,Ae=null});let Uo=null,Kd=()=>{Uo&&(Uo(),Uo=null),o.colorScheme==="auto"&&(Uo=zr(()=>{lr(e,o)}))};Kd(),je.push(()=>{Uo&&(Uo(),Uo=null)}),je.push(i);let ka=o.features?.streamAnimation;if(ka?.type&&ka.type!=="none"){let l=Gr(ka.type,ka.plugins);l&&($i(l,e),je.push(()=>lf(e)))}let gs=ji(vt),Gd=ji(Gt),Jd=ji(ft),fs=[gs,Gd,Jd];je.push(()=>{fs.forEach(l=>l.destroy())});let zo=null,_,qo=null,Xd=!1,Yd=0,Qd=null,Zd=l=>l.reduce((g,m)=>m.role==="user"?g+1:g,0),ep=l=>{for(let g=l.length-1;g>=0;g--)if(or(l[g]))return l[g].id??null;return null},tp=!1,Qm=()=>{tp||o.debug!==!0||(tp=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but copy.showWelcomeCard is false, so no starters render. Use "auto" or "composer".'))},np=!1,op=!1,rp=(l,g)=>{np||o.debug!==!0||!g.enabled||g.expose||Xd||op&&(_.isStreaming()||l.some(or)||(np=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},ms=l=>{if(!_)return;let g=l??_.getMessages(),m=ee=>{ee.render([],_,z,g)},x=ee=>{fs.forEach(pe=>{pe!==ee&&m(pe)})};qo&&(Zd(g)>Yd||ep(g)!==Qd)&&(qo=null);let M=To(o);rp(g,M);let P=M.enabled?oi(g):null,Y=qo??P,$=qo?"host":"agent";if(Y){let ee=o.suggestions?.followUps,pe=ee?.placement??(ee?"auto":"composer"),Ce=(pe==="auto"?N()?"composer":"after-message":pe)==="after-message"?Jd:gs;x(Ce),Ce.render(Y,_,z,g,o.suggestionChipsConfig,{source:$,surface:"followUp",variant:ee?.variant??"chip",behavior:ee?.behavior??"send",overflow:ee?.overflow??"scroll",maxItems:ee?.maxItems??4,config:o,plugins:s});return}if(g.some(ee=>ee.role==="user")){fs.forEach(m);return}let J=o.suggestions?.starters;if(J){let ee=o.copy?.showWelcomeCard!==!1,pe=J.placement??"auto",ae=pe==="auto"?ee?"welcome":"composer":pe;if(ae==="welcome"&&!ee){Qm(),fs.forEach(m);return}let Ce=ae==="welcome"?Gd:gs;x(Ce),Ce.render(J.items??o.suggestionChips,_,z,g,o.suggestionChipsConfig,{surface:"starter",variant:J.variant??"card",behavior:J.behavior??"send",overflow:J.overflow??"wrap",maxItems:J.maxItems??4,config:o,plugins:s});return}x(gs),gs.render(o.suggestionChips,_,z,g,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},sp=()=>{qo&&(qo=null,ms())},Zm=l=>{let g=Array.isArray(l)?[...l]:[];if(!g.length){sp();return}let m=_?_.getMessages():[];qo=g,Xd=!0,Yd=Zd(m),Qd=ep(m),ms(m)},Cn=!1,Vo=Gg(),wr=new Map,Ko=new Map,co=new Map,Ll=0,eh=Kn()!==null,sn=Bi(),gn=0,po=null,fn=!1,Pa=!1,uo=0,wn=null,Go=null,Rl=!1,La=!1,hs=null,ys=!0,Ra=!1,Ia=null,Wa=!1,Jo=()=>{Wa=!0},Il=null,th=4,Ha=24,nh=80,Wl=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ap=o.voiceRecognition?.autoResume??!1,jn=l=>{d.emit("voice:state",{active:Ge.active,source:l,timestamp:Date.now()})},An=()=>{E(l=>({...l,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},oh=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=pd(u.voiceState),g=!!l.active,m=Number(l.timestamp??0);Ge.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-m<Ox&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),jn("restore"),_.isVoiceActive()&&Er()}):Fa("restore"))},1e3)},rh=()=>_?Qf(_.getMessages()).filter(l=>!l.__skipPersist):[],Ba=null,ip=(l,g)=>{typeof console<"u"&&console.error(l,g)},Hl=(l,g)=>{let m=()=>{try{let Y=l();return!Y||typeof Y.then!="function"?null:Promise.resolve(Y).catch($=>{ip(g,$)})}catch(Y){return ip(g,Y),null}},x=Ba,M=x?x.then(()=>m()??void 0):m();if(!M)return;let P=M.finally(()=>{Ba===P&&(Ba=null)});Ba=P};function Bl(l){if(!c?.save)return;let m={messages:l?Qf(l):_?rh():[],metadata:u,artifacts:vn.artifacts,selectedArtifactId:vn.selectedId};Hl(()=>c.save(m),"[AgentWidget] Failed to persist state:")}let Ar=null,lp=()=>Oe.querySelector("#persona-scroll-container")||le,bs=()=>{Ar!==null&&(cancelAnimationFrame(Ar),Ar=null),fn=!1},cp=()=>{po!==null&&(cancelAnimationFrame(po),po=null),Pa=!1,bs()},sh=()=>Cn&&Ol()&&(un()!=="anchor-top"||Rd()),Dl=()=>{let l=so()||"Jump to latest",g=sh();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),uo>0?(_o.textContent=String(uo),_o.style.display="",Rt.setAttribute("aria-label",`${l} (${uo} new)`)):(_o.textContent="",_o.style.display="none",Rt.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},dp=()=>{uo!==0&&(uo=0,Dl())},Ol=()=>ao()?!sn.isFollowing():!Do(le,Ha),an=()=>{if(!zm()||Ue){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==be&&be.appendChild(Rt),br();let g=On(le)>0&&Ol();g?Dl():dp(),Rt.style.display=g?"":"none"},vs=()=>{sn.pause()&&(cp(),an())},go=()=>{sn.resume(),dp(),an()},fo=(l=!1)=>{ao()&&sn.isFollowing()&&(!l&&!Cn||(po!==null&&(cancelAnimationFrame(po),po=null),Pa=!0,po=requestAnimationFrame(()=>{po=null,Pa=!1,sn.isFollowing()&&ah(lp(),l?220:140)})))},pp=(l,g,m,x=()=>!0)=>{let M=l.scrollTop,P=g(),Y=P-M;if(bs(),Math.abs(Y)<1){fn=!0,l.scrollTop=P,gn=l.scrollTop,fn=!1;return}let $=performance.now();fn=!0;let J=pe=>1-Math.pow(1-pe,3),ee=pe=>{if(!x()){bs();return}let ae=g();ae!==P&&(P=ae,Y=P-M);let Ce=pe-$,Ve=Math.min(Ce/m,1),pt=J(Ve),et=M+Y*pt;l.scrollTop=et,gn=l.scrollTop,Ve<1?Ar=requestAnimationFrame(ee):(l.scrollTop=P,gn=l.scrollTop,Ar=null,fn=!1)};Ar=requestAnimationFrame(ee)},ah=(l,g=500)=>{let m=On(l)-l.scrollTop;if(Math.abs(m)<1){gn=l.scrollTop;return}if(Math.abs(m)>=nh){bs(),fn=!0,l.scrollTop=On(l),gn=l.scrollTop,fn=!1;return}pp(l,()=>On(l),g,()=>sn.isFollowing())},up=()=>{let l=lp();fn=!0,l.scrollTop=On(l),gn=l.scrollTop,fn=!1,an()},gp=l=>{let g=0,m=l;for(;m&&m!==le;)g+=m.offsetTop,m=m.offsetParent;return g},ih=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},Da=()=>Zg(ih(),le),fp=()=>{if(qm()!=="last-user-turn")return!1;let l=_?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(P=>P.role==="user");if(!g)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=le.querySelector(`[data-message-id="${m}"]`);if(!x)return!1;let M=Math.min(Math.max(0,gp(x)-Pd()),On(le));return fn=!0,le.scrollTop=M,gn=le.scrollTop,fn=!1,un()==="follow"&&!Do(le,Ha)&&sn.pause(),an(),!0},mp=l=>{io.style.height=`${Math.max(0,Math.round(l))}px`,wn&&(wn.spacerHeight=Math.max(0,l))},xs=()=>{Go!==null&&(cancelAnimationFrame(Go),Go=null),bs(),wn=null,io.style.height="0px"},hp=l=>{Go!==null&&cancelAnimationFrame(Go),Go=requestAnimationFrame(()=>{Go=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=le.querySelector(`[data-message-id="${g}"]`);if(!m)return;let x=gp(m),M=wn?.spacerHeight??0,P=le.scrollHeight-M,{targetScrollTop:Y,spacerHeight:$}=ef({anchorOffsetTop:x,topOffset:Pd(),viewportHeight:le.clientHeight,contentHeight:P});wn={initialSpacerHeight:$,contentHeightAtAnchor:P,spacerHeight:$},mp($),pp(le,()=>Y,220)})},lh=()=>{if(ao()){if(!sn.isFollowing()||Do(le,1))return;fo(!Cn);return}if(wn&&wn.initialSpacerHeight>0){let l=le.scrollHeight-wn.spacerHeight,g=tf({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:l});g!==wn.spacerHeight&&mp(g)}an()},ch=l=>{let g=un();g==="follow"?(go(),fo(!0)):g==="anchor-top"&&(ys=!1,Ra=!0,Wa=!1,Ia=l,hp(l))},dh=()=>{if(un()==="anchor-top"){if(Ra){ys=!1;return}ys=!0,xs(),go(),fo(!0)}},ph=l=>{if(un()!=="anchor-top"||!Ra||Wa||Da())return;let g=hs===null;for(let m of l){if(!g){m.id===hs&&(g=!0);continue}if(Qg(m)){if(m.id===Ia)return;Ia=m.id,hp(m.id);return}}},uh=l=>{let g=new Map;l.forEach(m=>{let x=Wl.get(m.id);g.set(m.id,{streaming:m.streaming,role:m.role}),!x&&m.role==="assistant"&&(d.emit("assistant:message",m),!La&&(un()!=="anchor-top"||Rd())&&Ol()&&(uo+=1,Dl(),an(),Wd(uo===1?"1 new message below.":`${uo} new messages below.`))),m.role==="assistant"&&x?.streaming&&m.streaming===!1&&d.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(x?m.approval.status!=="pending"&&d.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):d.emit("approval:requested",{approval:m.approval,message:m}))}),Wl.clear(),g.forEach((m,x)=>{Wl.set(x,m)})},Oa=(l,g)=>{let m=g==="user"?"user":"assistant",x=o.layout?.messages?.[m],M=x?.width??"content",P=x?.maxWidth??(M==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${g}`,`persona-message-width-${M}`),l.classList.toggle("persona-justify-end",g==="user"),l.setAttribute("data-message-role",g),l.setAttribute("data-message-width",M),l.style.setProperty("--persona-message-row-max-width",P)},Xo=(l,g)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${l}`,m.setAttribute("data-wrapper-id",l),Oa(m,g),m},gh=(l,g,m)=>{let x=document.createElement("div"),P=(()=>{let B=s.find(Le=>Le.renderLoadingIndicator);if(B?.renderLoadingIndicator)return B.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Y=(B,Le)=>Le==null?!1:typeof Le=="string"?(B.textContent=Le,!0):(B.appendChild(Le),!0),$=new Set,J=new Map,ee=new Set,pe=s.some(B=>B.renderAskUserQuestion),ae=[],Ce=[],Ve=o.enableComponentStreaming!==!1,pt=o.approval!==!1,et=[];if(g.forEach(B=>{$.add(B.id),J.set(B.id,B.role);let Le=pe&&Jn(B),_e=pt&&B.variant==="approval"&&!!B.approval,Me=!Le&&B.role==="assistant"&&!B.variant&&Ve&&ma(B);!_e&&co.has(B.id)&&(l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),co.delete(B.id)),!Me&&Ko.has(B.id)&&(l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),Ko.delete(B.id));let St=Jn(B)?`:${B.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${B.agentMetadata?.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=Kg(B,Ll)+St,Nt=Le||_e||Me?null:Jg(Vo,B.id,ut);if(Nt){x.appendChild(Nt.cloneNode(!0)),Jn(B)&&B.toolCall?.id&&B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(ee.add(B.toolCall.id),Or(B,o,Be.composerOverlay));return}let gt=null,en=s.find($e=>!!(B.variant==="reasoning"&&$e.renderReasoning||B.variant==="tool"&&$e.renderToolCall||!B.variant&&$e.renderMessage)),Ht=o.layout?.messages;if(Jn(B)&&B.agentMetadata?.askUserQuestionAnswered===!0){wr.delete(B.id),l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime");return}if(or(B)&&To(o).enabled)return;if(Jn(B)&&o.features?.askUserQuestion?.enabled!==!1){let $e=s.find(jt=>typeof jt.renderAskUserQuestion=="function");if($e&<.current){let jt=wr.get(B.id),Ut=jt!==ut,wt=null;if(Ut){let{payload:Xe,complete:De}=Xn(B),yt=B.id,zt=()=>lt.current?.getMessages().find(yn=>yn.id===yt);wt=$e.renderAskUserQuestion({message:B,payload:Xe,complete:De,resolve:yn=>{let Ls=zt();Ls&<.current?.resolveAskUserQuestion(Ls,yn)},dismiss:()=>{let yn=zt();yn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(yn),lt.current?.resolveAskUserQuestion(yn,"(dismissed)"))},config:o})}let ct=jt!=null;if(Ut&&wt===null&&!ct){B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(ee.add(B.toolCall.id),Or(B,o,Be.composerOverlay));return}let mt=Xo(B.id,B.role);mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),ae.push({messageId:B.id,fingerprint:ut,bubble:wt});return}else{B.agentMetadata?.awaitingLocalTool===!0&&!B.agentMetadata?.askUserQuestionAnswered&&(ee.add(B.toolCall.id),Or(B,o,Be.composerOverlay));return}}else if(_e){let $e=s.find(ct=>typeof ct.renderApproval=="function")??a,Ut=co.get(B.id)!==ut,wt=null;if(Ut&&$e?.renderApproval){let ct=B.id,mt=(Xe,De)=>{let yt=lt.current?.getMessages().find(zt=>zt.id===ct);yt?.approval&&(yt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(yt.id,Xe):lt.current?.resolveApproval(yt.approval,Xe,De))};wt=$e.renderApproval({message:B,defaultRenderer:()=>el(B,o),config:o,approve:Xe=>mt("approved",Xe),deny:Xe=>mt("denied",Xe)})}if(Ut&&wt===null)l.querySelector(`#wrapper-${B.id}`)?.removeAttribute("data-preserve-runtime"),co.delete(B.id),gt=el(B,o);else{let ct=Xo(B.id,B.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),x.appendChild(ct),et.push({messageId:B.id,fingerprint:ut,bubble:wt});return}}else if(en)if(B.variant==="reasoning"&&B.reasoning&&en.renderReasoning){if(!fe)return;gt=en.renderReasoning({message:B,defaultRenderer:()=>Xc(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&en.renderToolCall){if(!te)return;gt=en.renderToolCall({message:B,defaultRenderer:()=>Qc(B,o),config:o})}else en.renderMessage&&(gt=en.renderMessage({message:B,defaultRenderer:()=>{let $e=Yr(B,m,Ht,o.messageActions,We,{loadingIndicatorRenderer:P,widgetConfig:o});return B.role!=="user"&&ld($e,B,o,_),$e},config:o}));if(!gt&&Me){let $e=cl(B);if($e){let jt=Ko.get(B.id),Ut=jt!==ut,wt=o.wrapComponentDirectiveInBubble!==!1&&kn.getOptions($e.component)?.bubbleChrome!==!1,ct=null;if(Ut){let mt=ll($e,{config:o,message:B,transform:m});if(mt&&$e.component==="PersonaArtifactInline"){let Xe=mt.hasAttribute("data-artifact-inline")?mt:mt.querySelector("[data-artifact-inline]"),De=Xe?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,zt=De?l.querySelector(`#wrapper-${B.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Xe&&zt&&zt!==Xe&&$g(zt)&&(Xe===mt?mt=zt:Xe.replaceWith(zt))}if(mt)if(wt){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${B.id}`,Xe.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let De=document.createElement("div");De.className="persona-mb-3 persona-text-sm persona-leading-relaxed",De.innerHTML=m({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Xe.appendChild(De)}Xe.appendChild(mt),ct=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${B.id}`,Xe.setAttribute("data-message-id",B.id),Xe.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let De=document.createElement("div");De.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",De.innerHTML=m({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Xe.appendChild(De)}Xe.appendChild(mt),ct=Xe}}if(ct||jt!=null){let mt=Xo(B.id,B.role);mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),Ce.push({messageId:B.id,fingerprint:ut,bubble:ct});return}}}if(!gt)if(B.variant==="reasoning"&&B.reasoning){if(!fe)return;gt=Xc(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!te)return;gt=Qc(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;gt=el(B,o)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&B.role==="user"?gt=$e.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):$e?.renderAssistantMessage&&B.role==="assistant"?gt=$e.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):gt=Yr(B,m,$e,o.messageActions,We,{loadingIndicatorRenderer:P,widgetConfig:o}),B.role!=="user"&>&&ld(gt,B,o,_)}let Re=Xo(B.id,B.role);Re.appendChild(gt),Xg(Vo,B.id,ut,Re),x.appendChild(Re)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let _e=Le.getAttribute("data-persona-ask-sheet-for");_e&&!ee.has(_e)&&Ao(Be.composerOverlay,_e)}),o.features?.toolCallDisplay?.grouped){let B=[],Le=[],_e=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Me=>{if(Me.variant==="tool"&&Me.toolCall&&te){Le.push(Me);return}Me.variant==="reasoning"&&!fe||((Le.length>1||_e&&Le.length>0)&&B.push(Le),Le=[])}),(Le.length>1||_e&&Le.length>0)&&B.push(Le),B.forEach(Me=>{let St=Me.map($e=>Array.from(x.children).find(jt=>jt instanceof HTMLElement&&jt.getAttribute("data-wrapper-id")===$e.id)).filter($e=>!!$e);if(St.length<(_e?1:2))return;let ut=Xo(`tool-group-${Me[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Nt=document.createElement("div");Nt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Nt.setAttribute("data-persona-tool-group","true");let gt=document.createElement("div");gt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",gt.id=`tool-group-summary-${Me[0].id}`;let en=`Called ${Me.length} ${Me.length===1?"tool":"tools"}`,Ht=o.toolCall?.renderGroupedSummary?.({messages:Me,toolCalls:Me.map($e=>$e.toolCall).filter($e=>!!$e),defaultSummary:en,config:o});Y(gt,Ht)||(gt.textContent=en);let Re=document.createElement("div");Re.className="persona-tool-group-stack persona-flex persona-flex-col",Re.id=`tool-group-stack-${Me[0].id}`,Re.setAttribute("data-persona-tool-group-stack","true"),Nt.appendChild(gt),_e||Nt.appendChild(Re),ut.appendChild(Nt),St[0].before(ut),St.forEach(($e,jt)=>{if(_e){$e.remove();return}$e.style.setProperty("--persona-message-row-max-width","100%");let Ut=document.createElement("div");Ut.className="persona-tool-group-item persona-relative",Ut.setAttribute("data-persona-tool-group-item","true"),jt<St.length-1&&Ut.setAttribute("data-persona-tool-group-connector","true"),Ut.appendChild($e),Re.appendChild(Ut)})})}Yg(Vo,$);let ln=g.some(B=>B.role==="assistant"&&B.streaming),Et=g[g.length-1],Wt=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(Cn&&g.some(B=>B.role==="user")&&!ln&&!Wt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:pr},Le=s.find(Me=>Me.renderLoadingIndicator),_e=null;if(Le?.renderLoadingIndicator&&(_e=Le.renderLoadingIndicator(B)),_e===null&&o.loadingIndicator?.render&&(_e=o.loadingIndicator.render(B)),_e===null&&(_e=pr()),_e){let Me=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Me.className=St?Gc("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Me.setAttribute("data-typing-indicator","true"),St&&(Me.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Me.appendChild(_e);let Nt=Xo("typing-indicator","assistant");Nt.appendChild(Me),x.appendChild(Nt)}}if(!Cn&&g.length>0){let B=g[g.length-1],Le={config:o,lastMessage:B,messageCount:g.length},_e=s.find(St=>St.renderIdleIndicator),Me=null;if(_e?.renderIdleIndicator&&(Me=_e.renderIdleIndicator(Le)),Me===null&&o.loadingIndicator?.renderIdle&&(Me=o.loadingIndicator.renderIdle(Le)),Me){let St=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;St.className=ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(Me);let Nt=Xo("idle-indicator","assistant");Nt.appendChild(St),x.appendChild(Nt)}}if(bu(x),Hi(l,x),tc(l),ae.length>0)for(let{messageId:B,fingerprint:Le,bubble:_e}of ae){let Me=l.querySelector(`#wrapper-${B}`);Me&&(Oa(Me,J.get(B)??"assistant"),_e!==null&&(Me.replaceChildren(_e),Me.setAttribute("data-bubble-fp",Le),wr.set(B,Le)))}if(wr.size>0)for(let B of wr.keys())$.has(B)||wr.delete(B);if(Ce.length>0)for(let{messageId:B,fingerprint:Le,bubble:_e}of Ce){let Me=l.querySelector(`#wrapper-${B}`);Me&&(Oa(Me,J.get(B)??"assistant"),_e!==null&&(Me.replaceChildren(_e),Me.setAttribute("data-bubble-fp",Le),Ko.set(B,Le)))}if(Ko.size>0)for(let B of Ko.keys())$.has(B)||Ko.delete(B);if(et.length>0)for(let{messageId:B,fingerprint:Le,bubble:_e}of et){let Me=l.querySelector(`#wrapper-${B}`);Me&&(Oa(Me,J.get(B)??"assistant"),_e!==null&&(Me.replaceChildren(_e),Me.setAttribute("data-bubble-fp",Le),co.set(B,Le)))}if(co.size>0)for(let B of co.keys())$.has(B)||co.delete(B)},Cs=(l,g,m)=>{gh(l,g,m),$d()},ws=null,fh=()=>{if(ws)return;let l=m=>{let x=m.composedPath();x.includes(Oe)||Ye&&x.includes(Ye)||dt(!1,"user")};ws=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},yp=()=>{if(!ws)return;(e.ownerDocument??document).removeEventListener("pointerdown",ws,!0),ws=null};je.push(()=>yp());let As=null,mh=()=>{if(As)return;let l=m=>{m.key==="Escape"&&(m.isComposing||dt(!1,"user"))};As=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},bp=()=>{if(!As)return;(e.ownerDocument??document).removeEventListener("keydown",As,!0),As=null};je.push(()=>bp());let Ss=!1,vp=new Set,hh=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},Sr=()=>{if(!N())return;let l=Be.peekBanner,g=Be.peekTextNode;if(!l||!g)return;if(Z){l.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],x;for(let Et=m.length-1;Et>=0;Et--){let Wt=m[Et];if(Wt.role==="assistant"&&Wt.content){x=Wt;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let M=x.content,P=!!x.streaming,Y=hh(),$=Ni(Y),J=$.type!=="none"?Gr($.type,Y?.plugins):null,ee=J?.isAnimating?.(x)===!0,pe=J!==null&&(P||ee);pe&&J&&!vp.has(J.name)&&($i(J,e),vp.add(J.name));let ae=pe&&J?.containerClass?J.containerClass:null,Ce=g.dataset.personaPeekStreamClass??null;Ce&&Ce!==ae&&(g.classList.remove(Ce),delete g.dataset.personaPeekStreamClass),ae&&Ce!==ae&&(g.classList.add(ae),g.dataset.personaPeekStreamClass=ae),pe?(g.style.setProperty("--persona-stream-step",`${$.speed}ms`),g.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ve=pe?Fi(M,$.buffer,J,x,P):M;if(pe&&$.placeholder==="skeleton"&&P&&(!Ve||!Ve.trim())){let Et=document.createElement("div"),Wt=oa();Wt.classList.add("persona-pill-peek__skeleton"),Et.appendChild(Wt),Hi(g,Et)}else{let Et=Math.max(0,Ve.length-100),Wt=Ve.length>100?Ve.slice(-100):Ve,B=Hn(Wt);if(!pe||!J){let Le=Ve.length>100?`\u2026${Wt}`:Wt;g.textContent!==Le&&(g.textContent=Le)}else{let Le=B;(J.wrap==="char"||J.wrap==="word")&&(Le=na(B,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Et}));let _e=document.createElement("div");if(_e.innerHTML=Le,J.useCaret&&Wt.length>0){let Me=_i(),St=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=St[St.length-1];ut?.parentNode?ut.parentNode.insertBefore(Me,ut.nextSibling):_e.appendChild(Me)}Hi(g,_e),J.onAfterRender?.({container:g,bubble:l,messageId:x.id,message:x,speed:$.speed,duration:$.duration})}}let ln=Cn||Ss;l.classList.toggle("persona-pill-peek--visible",ln)};if(N()){let l=Be.peekBanner;if(l){let x=M=>{M.preventDefault(),M.stopPropagation(),dt(!0,"user")};l.addEventListener("pointerdown",x),je.push(()=>{l.removeEventListener("pointerdown",x)})}let g=()=>{Ss||(Ss=!0,Sr())},m=()=>{Ss&&(Ss=!1,Sr())};ge.addEventListener("pointerenter",g),ge.addEventListener("pointerleave",m),je.push(()=>{ge.removeEventListener("pointerenter",g),ge.removeEventListener("pointerleave",m)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",m),je.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",m)}))}let yh=l=>{let g=o.launcher?.composerBar??{},m=g.expandedSize??"anchored",x=g.bottomOffset??"16px",M=g.collapsedMaxWidth,P=g.expandedMaxWidth??"880px",Y=g.expandedTopOffset??"5vh",$=g.modalMaxWidth??"880px",J=g.modalMaxHeight??"min(90vh, 800px)",ee="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",ae=Oe.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Ye){let Ce=Ye.style;Ce.bottom=x,Ce.width=M??""}if(l&&m!=="fullscreen"){if(m==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=$,ae.maxWidth=ee,ae.maxHeight=J,ae.height=J;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${x} + ${pe})`,ae.top=Y,ae.width=P,ae.maxWidth=ee}},Ts=()=>{if(!U())return;if(N()){let ee=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=Z?"expanded":"collapsed";Oe.dataset.state=pe,Oe.dataset.expandedSize=ee,Ye&&(Ye.dataset.state=pe,Ye.dataset.expandedSize=ee),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),yh(Z),be.style.display=Z?"flex":"none",Ea(),Z?(fh(),mh()):(yp(),bp()),Sr();return}let l=Pt(o),g=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,M=g.innerWidth<=m,P=x&&M&&k,Y=on(o).reveal;Z?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0"),ge.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Xt&&(Xt.style.display="none")):(l?l&&(Y==="overlay"||Y==="push")&&!P?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.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"),ge.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"),ge.classList.remove("persona-scale-100","persona-opacity-100"),ge.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=l?"none":"":Xt&&(Xt.style.display=l?"none":""))},dt=(l,g="user")=>{if(!U()||Z===l)return;let m=Z;Z=l,Ts();let x=(()=>{let P=o.launcher?.sidebarMode??!1,Y=e.ownerDocument.defaultView??window,$=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,ee=Y.innerWidth<=J,pe=Pt(o)&&$&&ee,ae=N()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||$&&ee&&k||pe||ae})();if(Z&&x){if(!Rn){let P=e.getRootNode(),Y=P instanceof ShadowRoot?P.host:e.closest(".persona-host");Y&&(Rn=Oc(Y,o.launcher?.zIndex??Kt))}In||(In=Nc(e.ownerDocument))}else Z||(Rn?.(),Rn=null,In?.(),In=null);Z&&(ks(),fp()||(un()==="follow"?fo(!0):up()));let M={open:Z,source:g,timestamp:Date.now()};Z&&!m?d.emit("widget:opened",M):!Z&&m&&d.emit("widget:closed",M),d.emit("widget:state",{open:Z,launcherEnabled:k,voiceActive:Ge.active,streaming:_.isStreaming()})},Nl=l=>{Qe(l?"stop":"send"),K&&(K.disabled=l),fs.forEach(g=>{g.elements.forEach(m=>{m.toggleAttribute("data-disabled",l),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",l?"true":"false")}),g.buttons.forEach(m=>{m.disabled=l})}),we.dataset.personaComposerStreaming=l?"true":"false",we.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Fl=()=>{Ge.active||z&&z.focus()};d.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Fl(),200)});let xp=()=>{I.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",D.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",z.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let m=o.copy?.showWelcomeCard!==!1;l.style.display=m?"":"none",m?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(w.textContent=o.copy?.sendButtonLabel??"Send"),z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=u.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{E(g=>({...g,sessionId:l}))}});let Yo=null,bh=()=>{Yo==null&&(Yo=setInterval(()=>{let l=He.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Yo),Yo=null;return}let g=Date.now();l.forEach(m=>{let x=Number(m.getAttribute("data-tool-elapsed"));x&&(m.textContent=si(g-x))})},100))},_l=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((Y,$)=>_l(Y,g[$]));let m=l,x=g,M=Object.keys(m),P=Object.keys(x);return M.length===P.length&&M.every(Y=>Object.prototype.hasOwnProperty.call(x,Y)&&_l(m[Y],x[Y]))},Cp=l=>{let{content:g,rawContent:m,llmContent:x,...M}=l;return M},$l=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!ma(l),vh=(l,g,m)=>{if(l.length!==g.length)return!1;let x=l[m.index],M=g[m.index];return!x||!M||x.id!==m.id||M.id!==m.id?!1:(!Object.is(x.content,M.content)||!Object.is(x.rawContent,M.rawContent)||!Object.is(x.llmContent,M.llmContent))&&$l(x)&&$l(M)&&_l(Cp(x),Cp(M))},wp=null,Tr=null,Qo=null,Un=null,Na=l=>{wp=l;let g,m;Tr=null;for(let M=l.length-1;M>=0;M-=1){let P=l[M];if(!g&&P.role==="user"&&(g=P),!m&&P.role==="assistant"&&(m=P),!Tr&&$l(P)&&(Tr={index:M,id:P.id}),g&&m&&Tr)break}Cs(He,l,ne),Rc(He,vn.artifacts,{suppressTransition:Cn}),bh(),ms(l),fo(!Cn),uh(l),l.length===0&&(xs(),ys=!0,Ra=!1,Ia=null,Wa=!1),!Rl||La?(Rl=!0,hs=g?.id??null,Il=m?.id??null):g&&g.id!==hs?(hs=g.id,ch(g.id)):m&&m.id!==Il&&dh(),m&&(Il=m.id),ph(l);let x=Ge.lastUserMessageId;g&&g.id!==x&&(Ge.lastUserMessageId=g.id,d.emit("user:message",g)),Ge.lastUserMessageWasVoice=!!g?.viaVoice,Bl(l),Sr()},jl=()=>{Un!==null&&(cancelAnimationFrame(Un),Un=null);let l=Qo;Qo=null,l&&Na(l)},Ap=()=>{Un!==null&&cancelAnimationFrame(Un),Un=null,Qo=null},xh=l=>{let g=Qo??wp;if(Cn&&g&&Tr&&vh(g,l,Tr)){Qo=l,Un===null&&(Un=requestAnimationFrame(()=>{Un=null;let m=Qo;Qo=null,m&&Na(m)}));return}if(l.length===0){Ap(),Na(l);return}jl(),Na(l)};_=new jr(o,{onMessagesChanged(l){xh(l)},onStatusChanged(l){let g=o.statusIndicator??{};Lt(R,(x=>x==="idle"?g.idleText??Bt.idle:x==="connecting"?g.connectingText??Bt.connecting:x==="connected"?g.connectedText??Bt.connected:x==="error"?g.errorText??Bt.error:x==="paused"?g.pausedText??Bt.paused:x==="resuming"?g.resumingText??Bt.resuming:Bt[x])(l),g,l)},onStreamingChanged(l){l||(_?.getMessages().length===0?Ap():jl()),Cn=l,Nl(l),_&&Cs(He,_.getMessages(),ne),l||(fo(!0),op=!0,_&&rp(_.getMessages(),To(o))),an(),Wd(l?"Responding\u2026":"Response complete."),Sr()},onVoiceStatusChanged(l){if(d.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":zn(),Er();break;case"processing":zn(),Rh();break;case"speaking":zn(),Ih();break;default:l==="idle"&&_.isBargeInActive()?(zn(),Er(),K?.setAttribute("aria-label","End voice session")):(Ge.active=!1,zn(),jn("system"),An());break}},onArtifactsState(l){vn=l,l.artifacts.length===0&&(vr=!1),Rc(He,l.artifacts,{suppressTransition:Cn}),$n(),Bl()},onReconnect(l){let{executionId:g,lastEventId:m}=l.handle;l.phase==="paused"?d.emit("stream:paused",{executionId:g,after:m}):l.phase==="resuming"?d.emit("stream:resuming",{executionId:g,after:m,attempt:l.attempt??1}):d.emit("stream:resumed",{executionId:g,after:m})}}),lt.current=_,je.push(()=>_.cancel());let Ul=null;if(_.onReadAloudChange((l,g)=>{Fd=l,_d=g,$d();let m=l??Ul;l&&(Ul=l);let x=m?_.getMessages().find(M=>M.id===m)??null:null;d.emit("message:read-aloud",{messageId:m,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(Ul=null)}),Rl=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Se||o.onSSEEvent)&&_.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),Te?.processEvent(l,g),Se?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let Sp=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};v?v.then(l=>{if(l){if(l.metadata&&(u=pd(l.metadata),A.syncFromMetadata()),l.messages?.length){La=!0;try{_.hydrateMessages(l.messages)}finally{La=!1}}l.artifacts?.length&&_.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Sp()):Sp();let Tp=()=>{!N()||Z||!(o.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},Ch=(l,g)=>l?g?{refs:[...l.refs,...g.refs],finalize:async()=>{let[m,x]=await Promise.allSettled([l.finalize(),g.finalize()]),M=[];return m.status==="fulfilled"?M.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),x.status==="fulfilled"?M.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),zx(M)}}:l:g,wh=()=>{let g=z.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},Ms=!1,Ah=async l=>{let g=z.value.trim(),m=Mt?.hasAttachments()??!1,x=g?await(rn?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){z.value="",z.style.height="auto",Es(),rn?.clear();return}let M=rn?.collectForSubmit()??null,P=x?.kind==="server"?x.mentions:null,Y=Ch(M,P),$=x?.kind==="prompt"?x.sendText:g,J=!!M&&M.refs.length>0;if(!$&&!m&&!J&&!P)return;Tp();let ee;m&&(ee=[],ee.push(...Mt.getContentParts()),$&&ee.push(ko($)));let pe=x?.kind==="prompt"?void 0:wh();z.value="",z.style.height="auto",Es(),_.sendMessage($,{contentParts:ee,mentions:Y??void 0,contentSegments:pe,viaVoice:l?.viaVoice}),m&&Mt.clearAttachments(),M&&rn?.clear()},zl=async l=>{if(!Ms){Ms=!0;try{await Ah(l)}finally{Ms=!1}}},Mp=l=>{if(l.preventDefault(),_.isStreaming()){_.cancel(),Te?.reset(),Fe?.update();return}Ms||zl()},Sh=()=>o.features?.composerHistory!==!1,ql={...Hc},Vl=!1,Es=()=>{ql={...Hc}},Th=()=>_.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),Mh=l=>{if(!z)return;Vl=!0,z.value=l,z.dispatchEvent(new Event("input",{bubbles:!0})),Vl=!1;let g=z.value.length;z.setSelectionRange(g,g)},Eh=l=>{Vl||(l.isComposing||rn?.handleInput(l.inputType??void 0),Es())},kh=l=>{if(z&&!(!l.isComposing&&rn?.handleKeydown(l))){if(Sh()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=z.selectionStart===0&&z.selectionEnd===0,m=Vg({direction:l.key==="ArrowUp"?"up":"down",history:Th(),currentValue:z.value,atStart:g,state:ql});if(ql=m.state,m.handled){l.preventDefault(),m.value!==void 0&&Mh(m.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}if(Ms){l.preventDefault();return}Es(),l.preventDefault(),w.click()}}},Ep=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(be)&&(_.cancel(),Te?.reset(),Fe?.update(),Es(),l.preventDefault(),l.stopImmediatePropagation())},Ph=async l=>{if(o.attachments?.enabled!==!0||!Mt)return;let g=_x(l.clipboardData);g.length!==0&&(l.preventDefault(),await Mt.handleFiles(g))},mn=null,Wn=!1,Mr=null,Ct=null,kp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fa=(l="user")=>{if(Wn||_.isStreaming())return;let g=kp();if(!g)return;mn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;mn.continuous=!0,mn.interimResults=!0,mn.lang="en-US";let M=z.value;mn.onresult=P=>{let Y="",$="";for(let ee=0;ee<P.results.length;ee++){let pe=P.results[ee],ae=pe[0].transcript;pe.isFinal?Y+=ae+" ":$=ae}let J=M+Y+$;z.value=J,Mr&&clearTimeout(Mr),(Y||$)&&(Mr=window.setTimeout(()=>{z.value.trim()&&mn&&Wn&&(mo(),zl({viaVoice:!0}))},x))},mn.onerror=P=>{P.error!=="no-speech"&&mo()},mn.onend=()=>{if(Wn){let P=z.value.trim();P&&P!==M.trim()&&zl({viaVoice:!0}),mo()}};try{if(mn.start(),Wn=!0,Ge.active=!0,l!=="system"&&(Ge.manuallyDeactivated=!1),jn(l),An(),K){let P=o.voiceRecognition??{};Ct={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??o.sendButton?.size??"40")||24};let Y=P.recordingBackgroundColor,$=P.recordingIconColor,J=P.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Y??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let ee=K.querySelector("svg");ee&&ee.setAttribute("stroke",$)}J&&(K.style.borderColor=J),K.setAttribute("aria-label","Stop voice recognition")}}catch{mo("system")}},mo=(l="user")=>{if(Wn){if(Wn=!1,Mr&&(clearTimeout(Mr),Mr=null),mn){try{mn.stop()}catch{}mn=null}if(Ge.active=!1,jn(l),An(),K){if(K.classList.remove("persona-voice-recording"),Ct){K.style.backgroundColor=Ct.backgroundColor,K.style.color=Ct.color,K.style.borderColor=Ct.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}K.setAttribute("aria-label","Start voice recognition")}}},Lh=(l,g)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",M=l?.provider?.type==="custom";if(!(m||x||M))return null;let Y=h("div","persona-send-button-wrapper"),$=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button";let J=l?.tooltipText??"Start voice recognition";$.setAttribute("aria-label",J);let ee=l?.iconName??"mic",pe=g?.size??"40px",ae=l?.iconSize??pe,Ce=parseFloat(ae)||24,Ve=l?.backgroundColor??g?.backgroundColor,pt=l?.iconColor??g?.textColor;$.style.width=ae,$.style.height=ae,$.style.minWidth=ae,$.style.minHeight=ae,$.style.fontSize="18px",$.style.lineHeight="1",pt?$.style.color=pt:$.style.color="var(--persona-text, #111827)";let ln=re(ee,Ce,pt||"currentColor",1.5);ln?$.appendChild(ln):$.textContent="\u{1F3A4}",Ve?$.style.backgroundColor=Ve:$.style.backgroundColor="",l?.borderWidth&&($.style.borderWidth=l.borderWidth,$.style.borderStyle="solid"),l?.borderColor&&($.style.borderColor=l.borderColor),l?.paddingX&&($.style.paddingLeft=l.paddingX,$.style.paddingRight=l.paddingX),l?.paddingY&&($.style.paddingTop=l.paddingY,$.style.paddingBottom=l.paddingY),Y.appendChild($);let Et=l?.showTooltip??!1;return $t({anchor:$,trigger:Y,text:()=>$.getAttribute("aria-label")??J,enabled:Et}),{micButton:$,micButtonWrapper:Y}},Kl=()=>{if(!K||Ct)return;let l=o.voiceRecognition??{};Ct={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Gl=(l,g)=>{if(!K)return;let m=K.querySelector("svg");m&&m.remove();let x=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),M=re(l,x,g,1.5);M&&K.appendChild(M)},_a=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Er=()=>{if(!K)return;Kl();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,m=l.recordingIconColor,x=l.recordingBorderColor;if(_a(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let M=K.querySelector("svg");M&&M.setAttribute("stroke",m)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},Rh=()=>{if(!K)return;Kl();let l=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),m=l.processingIconName??"loader",x=l.processingIconColor??Ct?.color??"",M=l.processingBackgroundColor??Ct?.backgroundColor??"",P=l.processingBorderColor??Ct?.borderColor??"";_a(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=M,K.style.borderColor=P;let Y=x||"currentColor";K.style.color=Y,Gl(m,Y),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},Ih=()=>{if(!K)return;Kl();let l=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),m=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=l.speakingIconName??m,M=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??Ct?.color??"":Ct?.color??""),P=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),Y=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":Ct?.borderColor??"");_a(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=P,K.style.borderColor=Y;let $=M||"currentColor";K.style.color=$,Gl(x,$);let J=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",J),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},zn=()=>{K&&(_a(),Ct&&(K.style.backgroundColor=Ct.backgroundColor??"",K.style.color=Ct.color??"",K.style.borderColor=Ct.borderColor??"",Gl(Ct.iconName,Ct.color||"currentColor"),Ct=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},$a=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=_.getVoiceStatus(),g=_.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,An(),jn("user"),zn()});return}_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),Ge.manuallyDeactivated=!_.isVoiceActive(),An(),jn("user"),_.isVoiceActive()?Er():zn()});return}if(Wn){let l=z.value.trim();Ge.manuallyDeactivated=!0,An(),mo("user"),l&&(z.value="",z.style.height="auto",_.sendMessage(l))}else Ge.manuallyDeactivated=!1,An(),Fa("user")};Bd=$a,K&&(K.addEventListener("click",$a),je.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),zn()):mo("system"),K&&K.removeEventListener("click",$a)}));let Wh=d.on("assistant:complete",()=>{ap&&(Ge.active||Ge.manuallyDeactivated||ap==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),jn("auto"),_.isVoiceActive()&&Er()}):Fa("auto"))},600))});je.push(Wh);let Hh=d.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});je.push(Hh);let Pp=()=>{dt(!Z,"user")},Ft=null,Xt=null;if(k&&!N()){let{instance:l,element:g}=zc({config:o,plugins:s,onToggle:Pp});Ft=l,l||(Xt=g)}Ft?e.appendChild(Ft.element):Xt&&e.appendChild(Xt),Ts(),ms(),xp(),Nl(_.isStreaming()),fp()||(un()==="follow"?fo(!0):up()),oh(),q&&(!k||N()?setTimeout(()=>Fl(),0):Z&&setTimeout(()=>Fl(),200));let ks=()=>{if(N()){br(),Ts();return}let l=Pt(o),g=o.launcher?.sidebarMode??!1,m=l||g||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,M=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640,Y=x.innerWidth<=P,$=M&&Y&&k;try{if($){cs(),ds=Ma();return}let J=!1;oe&&(oe=!1,cs(),J=!0);let ee=Ma();if(!J&&ee!==ds&&(cs(),J=!0),ds=ee,J&&kl(),!k&&!l){ge.style.height="",ge.style.width="";return}if(!g&&!l){let ae=o?.launcher?.width??o?.launcherWidth??dn;ge.style.width=ae,ge.style.maxWidth=ae}if(Ta(),!m){let pe=x.innerHeight,ae=64,Ce=o.launcher?.heightOffset??0,Ve=Math.max(200,pe-ae),pt=Math.min(640,Ve),et=Math.max(200,pt-Ce);ge.style.height=`${et}px`}}finally{if(br(),Ts(),Z&&k){let ee=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),pe=o.launcher?.sidebarMode??!1,ae=o.launcher?.mobileFullscreen??!0,Ce=Pt(o)&&ae&&ee,Ve=pe||ae&&ee&&k||Ce;if(Ve&&!In){let pt=e.getRootNode(),et=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");et&&!Rn&&(Rn=Oc(et,o.launcher?.zIndex??Kt)),In=Nc(e.ownerDocument)}else Ve||(Rn?.(),Rn=null,In?.(),In=null)}}};ks();let Lp=e.ownerDocument.defaultView??window;if(Lp.addEventListener("resize",ks),je.push(()=>Lp.removeEventListener("resize",ks)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{br()});l.observe(we),je.push(()=>l.disconnect())}gn=le.scrollTop;let Rp=On(le),Ip=()=>{let l=le.scrollTop,g=On(le),m=g<Rp;if(Rp=g,!ao()){gn=l,an();return}let{action:x,nextLastScrollTop:M}=Di({following:sn.isFollowing(),currentScrollTop:l,lastScrollTop:gn,nearBottom:Do(le,Ha),userScrollThreshold:th,isAutoScrolling:fn||Pa||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gn=M,x==="resume"){Da()||go();return}x==="pause"&&vs()};if(le.addEventListener("scroll",Ip,{passive:!0}),je.push(()=>le.removeEventListener("scroll",Ip)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{lh(),tc(He)});l.observe(He),l.observe(le),je.push(()=>l.disconnect())}let Wp=()=>{ao()&&sn.isFollowing()&&Da()&&vs()},Hp=le.ownerDocument;Hp.addEventListener("selectionchange",Wp),je.push(()=>{Hp.removeEventListener("selectionchange",Wp)});let Bh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Bp=l=>{Bh.has(l.key)&&(Jo(),Ld()&&ao()&&sn.isFollowing()&&vs())},Dp=l=>{l.target?.closest("a, button, [tabindex], input, textarea, select")&&(Jo(),Ld()&&ao()&&sn.isFollowing()&&vs())};le.addEventListener("keydown",Bp),le.addEventListener("focusin",Dp),je.push(()=>{le.removeEventListener("keydown",Bp),le.removeEventListener("focusin",Dp)});let Op=l=>{if(l.deltaY!==0&&Jo(),!ao())return;let g=Oi({following:sn.isFollowing(),deltaY:l.deltaY,nearBottom:Do(le,Ha),resumeWhenNearBottom:!0});g==="pause"?vs():g==="resume"&&!Da()&&go()};le.addEventListener("wheel",Op,{passive:!0}),le.addEventListener("touchmove",Jo,{passive:!0}),le.addEventListener("pointerdown",Jo,{passive:!0}),je.push(()=>{le.removeEventListener("touchmove",Jo),le.removeEventListener("pointerdown",Jo)}),je.push(()=>le.removeEventListener("wheel",Op)),Rt.addEventListener("click",()=>{xs(),le.scrollTop=le.scrollHeight,gn=le.scrollTop,go(),fo(!0),an()}),je.push(()=>Rt.remove()),je.push(()=>{cp(),xs()});let Np=()=>{O&&(zo&&(O.removeEventListener("click",zo),zo=null),U()?(O.style.display="",zo=()=>{dt(!1,"user")},O.addEventListener("click",zo)):O.style.display="none")};Np(),(()=>{let{clearChatButton:l}=Be;l&&l.addEventListener("click",()=>{_.clearMessages(),Vo.clear(),go(),Ao(Be.composerOverlay);try{localStorage.removeItem(rs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),c?.clear&&Hl(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},A.syncFromMetadata(),Se?.clear(),Te?.reset(),Fe?.update()})})(),y&&y.addEventListener("submit",Mp);let Fp=[["keydown",kh],["input",Eh],["paste",Ph],["focus",Gm]],_p=l=>{if(l)for(let[g,m]of Fp)l.addEventListener(g,m)},$p=l=>{if(l)for(let[g,m]of Fp)l.removeEventListener(g,m)};_p(z),rn?.onComposerSwap((l,g)=>{$p(g),z=l,_p(l)});let jp=e.ownerDocument??document;jp.addEventListener("keydown",Ep,!0);let Up="persona-attachment-drop-active",Ps=0,Jl=()=>{Ps=0,be.classList.remove(Up)},kr=()=>o.attachments?.enabled===!0&&Mt!==null,zp=l=>{!ul(l.dataTransfer)||!kr()||(Ps++,Ps===1&&be.classList.add(Up))},qp=l=>{!ul(l.dataTransfer)||!kr()||(Ps--,Ps<=0&&Jl())},Vp=l=>{!ul(l.dataTransfer)||!kr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Kp=l=>{if(!ul(l.dataTransfer)||!kr())return;l.preventDefault(),l.stopPropagation(),Jl();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&Mt.handleFiles(g)},ho=!0;be.addEventListener("dragenter",zp,ho),be.addEventListener("dragleave",qp,ho),e.addEventListener("dragover",Vp,ho),e.addEventListener("drop",Kp,ho);let ja=e.ownerDocument,Gp=l=>{kr()&&l.preventDefault()},Jp=l=>{kr()&&l.preventDefault()};ja.addEventListener("dragover",Gp),ja.addEventListener("drop",Jp),je.push(()=>{y&&y.removeEventListener("submit",Mp),$p(z),jp.removeEventListener("keydown",Ep,!0),rn?.destroy()}),je.push(()=>{be.removeEventListener("dragenter",zp,ho),be.removeEventListener("dragleave",qp,ho),e.removeEventListener("dragover",Vp,ho),e.removeEventListener("drop",Kp,ho),ja.removeEventListener("dragover",Gp),ja.removeEventListener("drop",Jp),Jl()}),je.push(()=>{_.cancel()}),Ft?je.push(()=>{Ft?.destroy()}):Xt&&je.push(()=>{Xt?.remove()});let It={update(l){let g=o.toolCall,m=o.messageActions,x=o.layout?.messages,M=o.colorScheme,P=o.loadingIndicator,Y=o.iterationDisplay,$=o.features?.showReasoning,J=o.features?.showToolCalls,ee=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type;o=sl({...o,features:r},l),r=o.features,o=pa(o),Ea(),lr(e,o),ca(e,o),da(e,o),$n(),o.colorScheme!==M&&Kd();let Ce=ua.getForInstance(o.plugins);s.length=0,s.push(...Ce),k=o.launcher?.enabled??!0,F=o.launcher?.autoExpand??!1,fe=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,Q=o.features?.scrollToBottom??{};let Ve=un();me=o.features?.scrollBehavior??{},Ve!==un()&&(xs(),go()),Hd(),an();let pt=de;if(de=o.features?.showEventStreamToggle??!1,de&&!pt){if(Se||(Ae=new ia(ye),Se=new aa(Ee,Ae),Te=Te??new la,Ae.open().then(()=>Se?.restore()).catch(()=>{}),_.setSSEEventCallback((se,Ke)=>{o.onSSEEvent?.(se,Ke),Te?.processEvent(se,Ke),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!Ze&&Pe){let se=o.features?.eventStream?.classNames,Ke="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"+(se?.toggleButton?" "+se.toggleButton:"");Ze=h("button",Ke),Ze.style.width="28px",Ze.style.height="28px",Ze.style.color=Qt.actionIconColor,Ze.type="button",Ze.setAttribute("aria-label","Event Stream"),Ze.title="Event Stream";let ht=re("activity","18px","currentColor",1.5);ht&&Ze.appendChild(ht);let tt=Be.clearChatButtonWrapper,st=Be.closeButtonWrapper,qt=tt||st;qt&&qt.parentNode===Pe?Pe.insertBefore(Ze,qt):Pe.appendChild(Ze),Ze.addEventListener("click",()=>{Ue?is():Sl()})}}else!de&&pt&&(is(),Ze&&(Ze.remove(),Ze=null),Se?.clear(),Ae?.destroy(),Se=null,Ae=null,Te?.reset(),Te=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Ft&&!Xt){let{instance:se,element:Ke}=zc({config:o,plugins:s,onToggle:Pp});Ft=se,se||(Xt=Ke),e.appendChild(Ke)}Ft&&Ft.update(o),X&&o.launcher?.title!==void 0&&(X.textContent=o.launcher.title),ie&&o.launcher?.subtitle!==void 0&&(ie.textContent=o.launcher.subtitle);let et=o.layout?.header;if(et?.layout!==G&&Pe){let se=et?Jr(o,et,{showClose:U(),onClose:()=>dt(!1,"user")}):no({config:o,showClose:U(),onClose:()=>dt(!1,"user")});Tt.replaceHeader(se),Pe=Tt.header.element,H=Tt.header.iconHolder,X=Tt.header.headerTitle,ie=Tt.header.headerSubtitle,O=Tt.header.closeButton,G=et?.layout}else if(et){if(H&&(H.style.display=et.showIcon===!1?"none":""),X&&(X.style.display=et.showTitle===!1?"none":""),ie&&(ie.style.display=et.showSubtitle===!1?"none":""),O){let se=U()&&et.showCloseButton!==!1;O.style.display=se?"":"none"}if(Be.clearChatButtonWrapper){let se=et.showClearChat;if(se!==void 0){Be.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:Ke}=Be;Ke&&!Ke.classList.contains("persona-absolute")&&(se?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;Pe&&(Pe.style.display=Et?"":"none");let Wt=o.layout?.showFooter!==!1;we&&(we.style.display=Wt?"":"none"),br(),an(),k!==V?k?dt(F,"auto"):(Z=!0,Ts()):F!==S&&dt(F,"auto"),S=F,V=k,ks(),Np();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(g),Me=JSON.stringify(o.messageActions)!==JSON.stringify(m),St=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),ut=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,Nt=o.iterationDisplay!==Y,gt=(o.features?.showReasoning??!0)!==($??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ee)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(_e||Me||St||ut||Nt||gt)&&_&&(Ll++,Cs(He,_.getMessages(),ne));let Ht=o.features?.streamAnimation?.type;if(Ht!==ae&&Ht&&Ht!=="none"){let se=Gr(Ht,o.features?.streamAnimation?.plugins);se&&$i(se,e)}let Re=o.launcher??{},$e=Re.headerIconHidden??!1,jt=o.layout?.header?.showIcon,Ut=$e||jt===!1,wt=Re.headerIconName,ct=Re.headerIconSize??"48px";if(H){let se=be.querySelector(".persona-border-b-persona-divider"),Ke=se?.querySelector(".persona-flex-col");if(Ut)H.style.display="none",se&&Ke&&!se.contains(Ke)&&se.insertBefore(Ke,se.firstChild);else{if(H.style.display="",H.style.height=ct,H.style.width=ct,se&&Ke&&(se.contains(H)?H.nextSibling!==Ke&&(H.remove(),se.insertBefore(H,Ke)):se.insertBefore(H,Ke)),wt){let tt=parseFloat(ct)||24,st=re(wt,tt*.6,"currentColor",1);st?H.replaceChildren(st):H.textContent=Re.agentIconText??"\u{1F4AC}"}else if(Re.iconUrl){let tt=H.querySelector("img");if(tt)tt.src=Re.iconUrl,tt.style.height=ct,tt.style.width=ct;else{let st=document.createElement("img");st.src=Re.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=ct,st.style.width=ct,H.replaceChildren(st)}}else{let tt=H.querySelector("svg"),st=H.querySelector("img");(tt||st)&&H.replaceChildren(),H.textContent=Re.agentIconText??"\u{1F4AC}"}let ht=H.querySelector("img");ht&&(ht.style.height=ct,ht.style.width=ct)}}let mt=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(X&&(X.style.display=mt===!1?"none":""),ie&&(ie.style.display=Xe===!1?"none":""),O){let se=U()&&o.layout?.header?.showCloseButton!==!1;O.style.display=se?"":"none";let Ke=Re.closeButtonSize??"32px",ht=Re.closeButtonPlacement??"inline";O.style.height=Ke,O.style.width=Ke;let{closeButtonWrapper:tt}=Be,st=ht==="top-right",qt=tt?.classList.contains("persona-absolute");if(tt&&st!==qt)if(tt.remove(),st)tt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",be.style.position="relative",be.appendChild(tt);else{let bo=Re.clearChat?.placement??"inline",Is=Re.clearChat?.enabled??!0;tt.className=Is&&bo==="inline"?"":"persona-ml-auto";let Xp=be.querySelector(".persona-border-b-persona-divider");Xp&&Xp.appendChild(tt)}if(O.style.color=Re.closeButtonColor||Qt.actionIconColor,Re.closeButtonBackgroundColor?(O.style.backgroundColor=Re.closeButtonBackgroundColor,O.classList.remove("hover:persona-bg-gray-100")):(O.style.backgroundColor="",O.classList.add("hover:persona-bg-gray-100")),Re.closeButtonBorderWidth||Re.closeButtonBorderColor){let bo=Re.closeButtonBorderWidth||"0px",Is=Re.closeButtonBorderColor||"transparent";O.style.border=`${bo} solid ${Is}`,O.classList.remove("persona-border-none")}else O.style.border="",O.classList.add("persona-border-none");Re.closeButtonBorderRadius?(O.style.borderRadius=Re.closeButtonBorderRadius,O.classList.remove("persona-rounded-full")):(O.style.borderRadius="",O.classList.add("persona-rounded-full")),Re.closeButtonPaddingX?(O.style.paddingLeft=Re.closeButtonPaddingX,O.style.paddingRight=Re.closeButtonPaddingX):(O.style.paddingLeft="",O.style.paddingRight=""),Re.closeButtonPaddingY?(O.style.paddingTop=Re.closeButtonPaddingY,O.style.paddingBottom=Re.closeButtonPaddingY):(O.style.paddingTop="",O.style.paddingBottom="");let cn=Re.closeButtonIconName??"x",Sn=Re.closeButtonIconText??"\xD7";O.innerHTML="";let _t=re(cn,"28px","currentColor",1);_t?(_t.style.display="block",O.appendChild(_t)):O.textContent=Sn;let Vt=Re.closeButtonTooltipText??"Close chat",Vn=Re.closeButtonShowTooltip??!0;O.setAttribute("aria-label",Vt),tt&&$t({anchor:O,trigger:tt,text:()=>O?.getAttribute("aria-label")??Vt,enabled:Vn})}let{clearChatButton:De,clearChatButtonWrapper:yt}=Be;if(De){let se=Re.clearChat??{},Ke=se.enabled??!0,ht=o.layout?.header?.showClearChat,tt=ht!==void 0?ht:Ke,st=se.placement??"inline";if(yt){yt.style.display=tt?"":"none";let{closeButtonWrapper:qt}=Be;!N()&&qt&&!qt.classList.contains("persona-absolute")&&(tt?qt.classList.remove("persona-ml-auto"):qt.classList.add("persona-ml-auto"));let cn=st==="top-right",Sn=yt.classList.contains("persona-absolute");if(!N()&&cn!==Sn&&tt){if(yt.remove(),cn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",be.style.position="relative",be.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Vt=be.querySelector(".persona-border-b-persona-divider"),Vn=Be.closeButtonWrapper;Vt&&Vn&&Vn.parentElement===Vt?Vt.insertBefore(yt,Vn):Vt&&Vt.appendChild(yt)}let _t=Be.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(cn?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(tt){if(!N()){let bo=se.size??"32px";De.style.height=bo,De.style.width=bo}let qt=se.iconName??"refresh-cw",cn=se.iconColor??"";De.style.color=cn||Qt.actionIconColor,De.innerHTML="";let Sn=N()?"14px":"20px",_t=re(qt,Sn,"currentColor",1);if(_t&&(_t.style.display="block",De.appendChild(_t)),se.backgroundColor?(De.style.backgroundColor=se.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let bo=se.borderWidth||"0px",Is=se.borderColor||"transparent";De.style.border=`${bo} solid ${Is}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");se.borderRadius?(De.style.borderRadius=se.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),se.paddingX?(De.style.paddingLeft=se.paddingX,De.style.paddingRight=se.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),se.paddingY?(De.style.paddingTop=se.paddingY,De.style.paddingBottom=se.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Vt=se.tooltipText??"Clear chat",Vn=se.showTooltip??!0;De.setAttribute("aria-label",Vt),yt&&$t({anchor:De,trigger:yt,text:()=>De?.getAttribute("aria-label")??Vt,enabled:Vn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ga],yn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[yr.message,yr.messageAndClick];A=fa({parsers:zt,handlers:yn,getSessionMetadata:C,updateSessionMetadata:E,emit:d.emit,documentRef:typeof document<"u"?document:null}),ne=Zf(o,A,ue),_.updateConfig(o),Cs(He,_.getMessages(),ne),ms(),xp(),Nl(_.isStreaming());let Ls=o.voiceRecognition?.enabled===!0,Ua=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(Ls&&(Ua||kt))if(!K||!qe){let se=Lh(o.voiceRecognition,o.sendButton);se&&(K=se.micButton,qe=se.micButtonWrapper,nt.insertBefore(qe,j),K.addEventListener("click",$a),K.disabled=_.isStreaming())}else{let se=o.voiceRecognition??{},Ke=o.sendButton??{},ht=se.iconName??"mic",tt=Ke.size??"40px",st=se.iconSize??tt,qt=parseFloat(st)||24;K.style.width=st,K.style.height=st,K.style.minWidth=st,K.style.minHeight=st;let cn=se.iconColor??Ke.textColor;K.innerHTML="";let Sn=re(ht,qt,cn||"currentColor",1.5);Sn?K.appendChild(Sn):K.textContent="\u{1F3A4}";let _t=se.backgroundColor??Ke.backgroundColor;_t?K.style.backgroundColor=_t:K.style.backgroundColor="",cn?K.style.color=cn:K.style.color="var(--persona-text, #111827)",se.borderWidth?(K.style.borderWidth=se.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),se.borderColor?K.style.borderColor=se.borderColor:K.style.borderColor="",se.paddingX?(K.style.paddingLeft=se.paddingX,K.style.paddingRight=se.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),se.paddingY?(K.style.paddingTop=se.paddingY,K.style.paddingBottom=se.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Vt=se.tooltipText??"Start voice recognition",Vn=se.showTooltip??!1;K.setAttribute("aria-label",Vt),qe&&$t({anchor:K,trigger:qe,text:()=>K?.getAttribute("aria-label")??Vt,enabled:Vn}),qe.style.display="",K.disabled=_.isStreaming()}else K&&qe&&(qe.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Wn&&mo());if(o.attachments?.enabled===!0){if(!Ot||!Ne){let se=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Jt||(Jt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Jt.style.display="none",y.insertBefore(Jt,z)),At||(At=document.createElement("input"),At.type="file",At.accept=(se.allowedTypes??Zn).join(","),At.multiple=(se.maxFiles??4)>1,At.style.display="none",At.setAttribute("aria-label","Attach files"),y.insertBefore(At,z)),Ot=h("div","persona-send-button-wrapper"),Ne=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ne.type="button",Ne.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let tt=se.buttonIconName??"paperclip",st=ht,qt=parseFloat(st)||40,cn=Math.round(qt*.6);Ne.style.width=st,Ne.style.height=st,Ne.style.minWidth=st,Ne.style.minHeight=st,Ne.style.fontSize="18px",Ne.style.lineHeight="1";let Sn=re(tt,cn,"currentColor",1.5);Sn?Ne.appendChild(Sn):Ne.textContent="\u{1F4CE}",Ne.addEventListener("click",Vt=>{Vt.preventDefault(),At?.click()}),Ot.appendChild(Ne);let _t=se.buttonTooltipText??"Attach file";$t({anchor:Ne,trigger:Ot,text:()=>Ne?.getAttribute("aria-label")??_t}),ze?ze.append(Ot):y.appendChild(Ot),!Mt&&At&&Jt&&(Mt=ir.fromConfig(se),Mt.setPreviewsContainer(Jt),At.addEventListener("change",async()=>{Mt&&At?.files&&(await Mt.handleFileSelect(At.files),At.value="")}))}else{Ot.style.display="";let se=o.attachments??{};At&&(At.accept=(se.allowedTypes??Zn).join(","),At.multiple=(se.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(be.querySelector(".persona-attachment-drop-overlay")?.remove(),be.appendChild(em(o.attachments?.dropOverlay)),Ne){let se=o.attachments??{},Ke=se.buttonTooltipText??"Attach file";Ne.setAttribute("aria-label",Ke),Ne.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,tt=re(se.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);tt?Ne.appendChild(tt):Ne.textContent="\u{1F4CE}",Ot&&$t({anchor:Ne,trigger:Ot,text:()=>Ne?.getAttribute("aria-label")??Ke})}}else Ot&&(Ot.style.display="none"),Mt&&Mt.clearAttachments(),be.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},Rs=Dt.useIcon??!1,qa=Dt.iconText??"\u2191",Pr=Dt.iconName,Va=Dt.tooltipText??"Send message",Xl=Dt.showTooltip??!1,Zo=Dt.size??"40px",qn=Dt.backgroundColor,er=Dt.textColor;if(Rs){if(w.style.width=Zo,w.style.height=Zo,w.style.minWidth=Zo,w.style.minHeight=Zo,w.style.fontSize="18px",w.style.lineHeight="1",er?w.style.color=er:w.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(w.innerHTML="",Pr){let se=parseFloat(Zo)||24,Ke=er?.trim()||"currentColor",ht=re(Pr,se,Ke,2);ht?w.appendChild(ht):w.textContent=qa}else w.textContent=qa;w.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",qn?(w.style.backgroundColor=qn,w.classList.remove("persona-bg-persona-primary")):(w.style.backgroundColor="",w.classList.add("persona-bg-persona-primary"))}else w.textContent=o.copy?.sendButtonLabel??"Send",w.style.width="",w.style.height="",w.style.minWidth="",w.style.minHeight="",w.style.fontSize="",w.style.lineHeight="",w.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",qn?(w.style.backgroundColor=qn,w.classList.remove("persona-bg-persona-accent")):w.classList.add("persona-bg-persona-accent"),er?w.style.color=er:w.classList.add("persona-text-white");Dt.borderWidth?(w.style.borderWidth=Dt.borderWidth,w.style.borderStyle="solid"):(w.style.borderWidth="",w.style.borderStyle=""),Dt.borderColor?w.style.borderColor=Dt.borderColor:w.style.borderColor="",Dt.paddingX?(w.style.paddingLeft=Dt.paddingX,w.style.paddingRight=Dt.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),Dt.paddingY?(w.style.paddingTop=Dt.paddingY,w.style.paddingBottom=Dt.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),_.isStreaming()||w.setAttribute("aria-label",Va),j&&$t({anchor:w,trigger:j,text:()=>w.getAttribute("aria-label")??Va,enabled:Xl});let Ka=o.layout?.contentMaxWidth??(N()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Ka?(He.style.maxWidth=Ka,He.style.marginLeft="auto",He.style.marginRight="auto",He.style.width="100%",y&&(y.style.maxWidth=Ka,y.style.marginLeft="auto",y.style.marginRight="auto"),vt&&(vt.style.maxWidth=Ka,vt.style.marginLeft="auto",vt.style.marginRight="auto")):(He.style.maxWidth="",He.style.marginLeft="",He.style.marginRight="",He.style.width="",y&&(y.style.maxWidth="",y.style.marginLeft="",y.style.marginRight=""),vt&&(vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight=""));let yo=o.statusIndicator??{},Dh=yo.visible??!0;if(R.style.display=Dh?"":"none",_){let se=_.getStatus();Lt(R,(ht=>ht==="idle"?yo.idleText??Bt.idle:ht==="connecting"?yo.connectingText??Bt.connecting:ht==="connected"?yo.connectedText??Bt.connected:ht==="error"?yo.errorText??Bt.error:Bt[ht])(se),yo,se)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Oh=yo.align==="left"?"persona-text-left":yo.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(Oh)},open(){U()&&dt(!0,"api")},close(){U()&&dt(!1,"api")},toggle(){U()&&dt(!Z,"api")},reconnect(){_.reconnectNow()},clearChat(){_n=!1,_.clearMessages(),Vo.clear(),go();try{localStorage.removeItem(rs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),c?.clear&&Hl(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},A.syncFromMetadata(),Se?.clear(),Te?.reset(),Fe?.update()},setMessage(l){return!z||_.isStreaming()?!1:(!Z&&U()&&dt(!0,"system"),z.value=l,z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let g=l?.trim()||z.value.trim();return g?(!Z&&U()&&dt(!0,"system"),z.value="",z.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!Z&&U()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,An(),_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),jn("user"),_.isVoiceActive()&&Er()})),!0):Wn?!0:kp()?(!Z&&U()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,An(),Fa("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,An(),jn("user"),zn()}),!0):!1:Wn?(Ge.manuallyDeactivated=!0,An(),mo("user"),!0):!1},injectMessage(l){return!Z&&U()&&dt(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!Z&&U()&&dt(!0,"system");let g=_.injectAssistantMessage(l);return he&&(he=!1,ve&&(clearTimeout(ve),ve=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(l){return!Z&&U()&&dt(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!Z&&U()&&dt(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!Z&&U()&&dt(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!Z&&U()&&dt(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!Z&&U()&&dt(!0,"system"),_.injectTestEvent(l)},async connectStream(l,g){return _.connectStream(l,g)},__pushEventStreamEvent(l){Se&&(Te?.processEvent(l.type,l.payload),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!de||!Se||Sl()},hideEventStream(){Ue&&is()},isEventStreamVisible(){return Ue},showArtifacts(){Zt(o)&&(_n=!1,vr=!0,$n(),Je?.setMobileOpen(!0))},hideArtifacts(){Zt(o)&&(_n=!0,$n())},upsertArtifact(l){return Zt(o)?(Bn(o.features?.artifacts,{artifactType:l.artifactType,...l.artifactType==="markdown"&&l.file?{file:l.file}:{},...l.presentation?{presentation:l.presentation}:{}})==="panel"&&(_n=!1,vr=!0),_.upsertArtifact(l)):null},selectArtifact(l){Zt(o)&&_.selectArtifact(l)},clearArtifacts(){Zt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return k&&!Z&&!N()||!z?!1:(z.focus(),!0)},async resolveApproval(l,g,m){let M=_.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===l);if(!M?.approval)throw new Error(`Approval not found: ${l}`);if(M.approval.toolType==="webmcp"){_.resolveWebMcpApproval(M.id,g);return}return _.resolveApproval(M.approval,g,m)},setFollowUpSuggestions(l){Zm(l)},clearFollowUpSuggestions(){sp()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(l){E(l)},on(l,g){return d.on(l,g)},off(l,g){d.off(l,g)},isOpen(){return U()&&Z},isVoiceActive(){return Ge.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:U()&&Z,launcherEnabled:k,voiceActive:Ge.active,streaming:_.isStreaming()}},showCSATFeedback(l){!Z&&U()&&dt(!0,"system");let g=He.querySelector(".persona-feedback-container");g&&g.remove();let m=dl({onSubmit:async(x,M)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(x,M),l?.onSubmit?.(x,M)},onDismiss:l?.onDismiss,...l});He.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!Z&&U()&&dt(!0,"system");let g=He.querySelector(".persona-feedback-container");g&&g.remove();let m=pl({onSubmit:async(x,M)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(x,M),l?.onSubmit?.(x,M)},onDismiss:l?.onDismiss,...l});He.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return _.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return _.submitNPSFeedback(l,g)},destroy(){jl(),Yo!=null&&(clearInterval(Yo),Yo=null),je.forEach(l=>l()),Oe.remove(),Ye?.remove(),Ft?.destroy(),Xt?.remove(),zo&&O.removeEventListener("click",zo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:m=>m?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=g,je.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=$=>{let J=$.detail;(!J?.instanceId||J.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",g),je.push(()=>{window.removeEventListener("persona:focusInput",g)}),de){let $=ee=>{let pe=ee.detail;(!pe?.instanceId||pe.instanceId===l)&&It.showEventStream()},J=ee=>{let pe=ee.detail;(!pe?.instanceId||pe.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",J),je.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",J)})}let m=$=>{let J=$.detail;(!J?.instanceId||J.instanceId===l)&&It.showArtifacts()},x=$=>{let J=$.detail;(!J?.instanceId||J.instanceId===l)&&It.hideArtifacts()},M=$=>{let J=$.detail;J?.instanceId&&J.instanceId!==l||J?.artifact&&It.upsertArtifact(J.artifact)},P=$=>{let J=$.detail;J?.instanceId&&J.instanceId!==l||typeof J?.id=="string"&&It.selectArtifact(J.id)},Y=$=>{let J=$.detail;(!J?.instanceId||J.instanceId===l)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",Y),je.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",Y)})}let hn=$x(o.persistState);if(hn&&U()){let l=jx(hn.storage),g=`${hn.keyPrefix}widget-open`,m=`${hn.keyPrefix}widget-voice`,x=`${hn.keyPrefix}widget-voice-mode`;if(l){let M=hn.persist?.openState&&l.getItem(g)==="true",P=hn.persist?.voiceState&&l.getItem(m)==="true",Y=hn.persist?.voiceState&&l.getItem(x)==="true";if(M&&setTimeout(()=>{It.open(),setTimeout(()=>{if(P||Y)It.startVoiceRecognition();else if(hn.persist?.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),hn.persist?.openState&&(d.on("widget:opened",()=>{l.setItem(g,"true")}),d.on("widget:closed",()=>{l.setItem(g,"false")})),hn.persist?.voiceState&&(d.on("voice:state",$=>{l.setItem(m,$.active?"true":"false")}),d.on("user:message",$=>{l.setItem(x,$.viaVoice?"true":"false")})),hn.clearOnChatClear){let $=()=>{l.removeItem(g),l.removeItem(m),l.removeItem(x)},J=()=>$();window.addEventListener("persona:clear-chat",J),je.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(f&&U()&&setTimeout(()=>{It.open()},0),Sr(),!eh){let l=Ir(()=>{_&&(Ll++,Vo.clear(),Cs(He,_.getMessages(),ne))});je.push(l)}return It};var tm=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},qx=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Vx=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Kx=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},nm=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},md=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=""},om=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",md(e)},ud=e=>{e.style.transition=""},gd=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=""},fd=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},fl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Gx=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Jx=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Xx=e=>{let t=Ro(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Yt(t,r)??r;return{inset:o(n?.inset,wi),canvasBackground:o(n?.canvasBackground,Ai)}},rm=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Yx=(e,t,n,o,r,s,a,i)=>{let d=on(s),p=d.reveal==="push",c=i!=null,u=i?.inset??"",v=i?.canvasBackground??"";Gx(e,t,n,o,p),Jx(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=C:!1;if(b&&E&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),gd(t),ud(o),om(o),fd(n),fl(r,o),rm(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Kt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(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"),om(o),qx(o,d.maxHeight),rm(o,c&&a,u,v),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",gd(t),ud(o),fd(n),fl(r,o);let W=d.animate?"transform 180ms ease":"none",A=d.side==="right"?"translateX(100%)":"translateX(-100%)",k=a?"translateX(0)":A;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=W,o.style.transform=k,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ud(o),md(o),fl(r,o);let W=tm(d.width,e.clientWidth),A=Math.max(0,e.clientWidth),k=d.animate?"margin-left 180ms ease":"none",F=d.side==="right"?a?-W:0:a?0:-W;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${A+W}px`,t.style.transition=k,t.style.marginLeft=`${F}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",gd(t),md(o),fd(n),fl(r,o);let W=d.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=a?d.width:"0px",k=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",F=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",Vx(o,d.maxHeight),o.style.overflow=W||F?"hidden":"visible",o.style.transition=k,W){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let q=c?`calc(${tm(d.width,e.clientWidth)}px - (2 * ${u}))`:d.width;r.style.width=q,r.style.minWidth=q,r.style.maxWidth=q,r.style.boxSizing="border-box"}}},Qx=(e,t)=>{let n=e.ownerDocument.createElement("div");return nm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){nm(n,o)},destroy(){n.remove()}}},Zx=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",p.appendChild(c),o.insertBefore(a,e),d.appendChild(e);let v=null,f=()=>{v?.disconnect(),v=null},b=null,C=()=>{b=t?.launcher?.detachedPanel===!0?Xx(t):null};C();let E=()=>{Yx(a,i,d,p,c,t,u,b)},L=null,W=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=zr(()=>{C(),E()}))},A=()=>{f(),on(t).reveal==="push"&&(typeof ResizeObserver>"u"||(v=new ResizeObserver(()=>{E()}),v.observe(a)))},k=!1,F=()=>{E(),A(),u&&!k&&a.dataset.personaDockMobileFullscreen!=="true"&&(k=!0,Kx(a,on(t)))},q=a.ownerDocument.defaultView,S=()=>{F()};return q?.addEventListener("resize",S),on(t).reveal==="push"?(i.appendChild(d),i.appendChild(p),a.appendChild(i)):(a.appendChild(d),a.appendChild(p)),F(),W(),{mode:"docked",host:c,shell:a,syncWidgetState(V){let G=V.launcherEnabled?V.open:!0;u!==G&&(u=G,F())},updateConfig(V){t=V,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),F(),W()},destroy(){q?.removeEventListener("resize",S),L?.(),L=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},ha=(e,t)=>Pt(t)?Zx(e,t):Qx(e,t);var eC=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},sm=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},hd=e=>{let t=eC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=ha(t,r),a,i=[],d=(E,L)=>{let A=!(L?.launcher?.enabled??!0)||Pt(L),k=o.createElement("div");if(k.setAttribute("data-persona-root","true"),A&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0",k.style.minWidth="0"),n){let F=E.attachShadow({mode:"open"});F.appendChild(k),sm(F,o)}else E.appendChild(k),sm(E,o);return t.id&&k.setAttribute("data-persona-instance",t.id),k},p=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},u=()=>{let E=d(s.host,r);a=gl(E,r,{debugTools:e.debugTools}),c()},v=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),e.onChatReady?.();let f=E=>{v(),s.destroy(),s=ha(t,E),r=E,u()},b={update(E){let L=sl(r??{},E),W=Pt(r),A=Pt(L),k=No(r),F=No(L);if(W!==A||k!==F){f(L);return}r=L,s.updateConfig(r),a.update(E),p()},destroy(){v(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(b,{get(E,L,W){if(L==="host")return s.host;if(L in E)return Reflect.get(E,L,W);let A=a[L];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function tC(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function nC(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:tC(o,n)?2:3}function am(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function ml(e,t){let n=t.trim();if(!n)return[...e].sort(am);let o=[];for(let r of e){let s=nC(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:am(r.item,s.item)),o.map(r=>r.item)}function oC(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function im(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>ml(e.items,t),resolve:e.resolve}}function lm(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>ml(t,oC(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var gm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),rC=new Set(["button","a","input","select","textarea","details","summary"]),sC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yd=/\b(product|card|item|listing|result)\b/i,vd=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,aC=3e3,iC=100;function fm(e){let t=typeof e.className=="string"?e.className:"";if(yd.test(t)||e.id&&yd.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&yd.test(o.value))return!0}return!1}function mm(e){return vd.test((e.textContent??"").trim())}function hm(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function lC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function cm(e){let t=e.match(vd);return t?t[0]:null}function dm(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function cC(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var dC="commerce-card",pC="result-card";function pm(e){return!fm(e)||!mm(e)||!hm(e)&&!lC(e)?0:5200}function um(e){return!fm(e)||mm(e)||!hm(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xd=[{id:dC,scoreElement(e){return pm(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||vd.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(pm(e)===0)return null;let{title:n,href:o}=dm(e),r=cm((e.textContent??"").trim())??cm(t.text)??"",s=cC(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
143
|
+
`)}},{id:pC,scoreElement(e){return um(e)},formatSummary(e,t){if(um(e)===0)return null;let{title:n,href:o}=dm(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
144
|
+
`)}}];function uC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function gC(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),p=e.rules??xd;return i==="simple"&&e.rules&&e.rules.length>0?(uC(),p=[]):i==="simple"&&(p=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function bd(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var fC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function mC(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"||rC.has(t)||n&&sC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ym(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 hC(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let p=0;p<e.attributes.length;p++){let c=e.attributes[p];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Cd(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${bd(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of fC){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${bd(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>bd(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function yC(e){return e==="static"?iC:aC}function bm(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Cd(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:mC(e),attributes:hC(e)}}function bC(e,t,n,o){let r=yC(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(r+=i,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function vC(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function xC(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let p=i,c=p.tagName.toLowerCase();if(gm.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ym(p)){i=a.nextNode();continue}let u=bm(p,e.maxTextLength),v=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!v&&!f){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:b,formattingRule:C}=bC(p,u,e.rules,n);r.push({el:p,domIndex:s,enriched:u,score:b,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((p,c)=>{let u=p.enriched.interactivity==="static"?1:0,v=c.enriched.interactivity==="static"?1:0;return u!==v?u-v:c.score!==p.score?c.score-p.score:p.domIndex-c.domIndex});let d=[];for(let p of r){if(d.length>=e.maxElements)break;vC(d,p)||d.push(p)}return d.sort((p,c)=>{let u=p.enriched.interactivity==="static"?1:0,v=c.enriched.interactivity==="static"?1:0;return u!==v?u-v:u===1&&c.score!==p.score?c.score-p.score:p.domIndex-c.domIndex}),d.map(p=>{let c;if(p.formattingRule?.formatSummary){let v=p.formattingRule.formatSummary(p.el,p.enriched,n);v&&(c=v)}let u={...p.enriched};return c&&(u.formattedSummary=c),u})}function CC(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,p=d.tagName.toLowerCase();if(gm.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!ym(d)){s=r.nextNode();continue}let c=bm(d,e.maxTextLength),u=c.text.length>0,v=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!v){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.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 vm(e={}){let t=gC(e),n=t.root??document.body;return n?t.mode==="simple"?CC(t,n):xC(t,n):[]}var hl=100;function xm(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
|
|
145
145
|
${s.map(a=>`- ${a.split(`
|
|
146
146
|
`).join(`
|
|
147
147
|
`)}`).join(`
|
|
148
|
-
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,
|
|
148
|
+
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,hl)}" (clickable)`);o.push(`Interactive elements:
|
|
149
149
|
${s.join(`
|
|
150
|
-
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,
|
|
150
|
+
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,hl)}" (navigable)`);o.push(`Navigation links:
|
|
151
151
|
${s.join(`
|
|
152
|
-
`)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,
|
|
152
|
+
`)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,hl)}" (input)`);o.push(`Form inputs:
|
|
153
153
|
${s.join(`
|
|
154
|
-
`)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,
|
|
154
|
+
`)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,hl)}"`);o.push(`Content:
|
|
155
155
|
${s.join(`
|
|
156
156
|
`)}`)}return o.join(`
|
|
157
157
|
|
|
158
|
-
`)}function
|
|
158
|
+
`)}function Cm(){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 wm(){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 Am(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Fn(e.colors.primary,.95),100:Fn(e.colors.primary,.9),200:Fn(e.colors.primary,.8),300:Fn(e.colors.primary,.7),400:Fn(e.colors.primary,.6),500:e.colors.primary,600:Fn(e.colors.primary,.8),700:Fn(e.colors.primary,.7),800:Fn(e.colors.primary,.6),900:Fn(e.colors.primary,.5),950:Fn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Sm(){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 Tm(){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 Fn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Mm(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var wC={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"}}},Em={components:{panel:{borderRadius:"0",shadow:"none"}}},wd={id:"shop",label:"Shopping Assistant",config:{theme:wC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:dn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Ad={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Em}},Sd={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Em}},Td={shop:wd,minimal:Ad,fullscreen:Sd};function km(e){return Td[e]}var Pm=hd;function Md(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Qn}/dist`}function ro(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function AC(e){if(e)return{getHeaders:ro(e.getHeaders),onFeedback:ro(e.onFeedback),onCopy:ro(e.onCopy),requestMiddleware:ro(e.requestMiddleware),actionHandlers:ro(e.actionHandlers),actionParsers:ro(e.actionParsers),postprocessMessage:ro(e.postprocessMessage),contextProviders:ro(e.contextProviders),streamParser:ro(e.streamParser)}}var Lm=`({ text, message }: any) => {
|
|
159
159
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
160
160
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
161
161
|
let cleanJson = jsonSource
|
|
@@ -168,7 +168,7 @@ ${s.join(`
|
|
|
168
168
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
169
169
|
} catch (e) { return null; }
|
|
170
170
|
return null;
|
|
171
|
-
}`,
|
|
171
|
+
}`,Rm=`function(ctx) {
|
|
172
172
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
173
173
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
174
174
|
var cleanJson = jsonSource
|
|
@@ -181,7 +181,7 @@ ${s.join(`
|
|
|
181
181
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
182
182
|
} catch (e) { return null; }
|
|
183
183
|
return null;
|
|
184
|
-
}`,
|
|
184
|
+
}`,Im=`(action: any, context: any) => {
|
|
185
185
|
if (action.type !== 'nav_then_click') return;
|
|
186
186
|
const payload = action.payload || action.raw || {};
|
|
187
187
|
const url = payload?.page;
|
|
@@ -198,7 +198,7 @@ ${s.join(`
|
|
|
198
198
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
199
199
|
window.location.href = targetUrl;
|
|
200
200
|
return { handled: true, displayText: text };
|
|
201
|
-
}`,
|
|
201
|
+
}`,Wm=`function(action, context) {
|
|
202
202
|
if (action.type !== 'nav_then_click') return;
|
|
203
203
|
var payload = action.payload || action.raw || {};
|
|
204
204
|
var url = payload.page;
|
|
@@ -215,26 +215,27 @@ ${s.join(`
|
|
|
215
215
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
216
216
|
window.location.href = targetUrl;
|
|
217
217
|
return { handled: true, displayText: text };
|
|
218
|
-
}`,
|
|
218
|
+
}`,SC=`(parsed: any) => {
|
|
219
219
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
220
220
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
221
221
|
if (parsed.action === 'message') return parsed.text || '';
|
|
222
222
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
223
223
|
return parsed.text || null;
|
|
224
|
-
}`,
|
|
224
|
+
}`,TC=`function(parsed) {
|
|
225
225
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
226
226
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
227
227
|
if (parsed.action === 'message') return parsed.text || '';
|
|
228
228
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
229
229
|
return parsed.text || null;
|
|
230
|
-
}`;function
|
|
231
|
-
`)}function
|
|
232
|
-
`)}function tC(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${da(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Bo(o,"theme",e.theme," "),e.launcher&&Bo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pl(e," ")),o.push(...ul(e," ",n)),o.push(...fl(e," ")),o.push(...gl(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${Xx}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${pm}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${pm}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${fm}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${fm}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
233
|
-
`)}function ym(e){let t=dl(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let d={};Object.entries(i).forEach(([p,c])=>{p!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(d[p]=c)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function nC(e,t){let n=ym(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="${vd(t)}/install.global.js" data-config='${s}'></script>`}function oC(e,t){let n=t?.hooks,o=dl(e),r=o!=="plain",s=vd(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${da(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Bo(a,"theme",e.theme," "),e.launcher&&Bo(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([i,d])=>{a.push(` ${i}: "${d}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,d])=>{typeof d=="string"?a.push(` ${i}: "${d}",`):typeof d=="boolean"&&a.push(` ${i}: ${d},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,d])=>{typeof d=="string"?a.push(` ${i}: "${d}",`):typeof d=="boolean"?a.push(` ${i}: ${d},`):typeof d=="number"&&a.push(` ${i}: ${d},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,d])=>{typeof d=="string"?a.push(` ${i}: "${d}",`):typeof d=="boolean"&&a.push(` ${i}: ${d},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([i,d])=>{a.push(` ${i}: ${d},`)}),a.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{a.push(` "${i}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...pl(e," ")),a.push(...ul(e," ",n)),a.push(...fl(e," ")),a.push(...gl(e," ")),a.push(...xd(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
|
|
234
|
-
`)}function
|
|
230
|
+
}`;function MC(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 yl(e){return e.parserType??MC(e.streamParser)??"plain"}function bl(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function vl(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function xl(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Cl(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
|
|
231
|
+
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function wl(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"?n.push(`${t} ${d}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${d}: ${p},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Ed(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 Hm(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),Hm(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Fo(e,t,n,o){n&&(e.push(`${o}${t}: {`),Hm(e,n,`${o} `),e.push(`${o}},`))}function ya(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Bm(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:AC(n.hooks)}:void 0;return t==="esm"?EC(o,r):t==="script-installer"?LC(o,r):t==="script-advanced"?IC(o,r):t==="react-component"?kC(o,r):t==="react-advanced"?PC(o,r):RC(o,r)}function EC(e,t){let n=t?.hooks,o=yl(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ya(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Fo(s,"theme",e.theme," "),e.launcher&&Fo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),s.push(...Cl(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...bl(e," ")),s.push(...vl(e," ",n)),s.push(...xl(e," ")),s.push(...wl(e," ")),s.push(...Ed(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
232
|
+
`)}function kC(e,t){let n=t?.hooks,o=yl(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${ya(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Fo(s,"theme",e.theme," "),e.launcher&&Fo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),s.push(...Cl(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...bl(e," ")),s.push(...vl(e," ",n)),s.push(...xl(e," ")),s.push(...wl(e," ")),s.push(...Ed(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
233
|
+
`)}function PC(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${ya(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Fo(o,"theme",e.theme," "),e.launcher&&Fo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...Cl(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...bl(e," ")),o.push(...vl(e," ",n)),o.push(...xl(e," ")),o.push(...wl(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${SC}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Lm}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Lm}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${Im}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${Im}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
234
|
+
`)}function Dm(e){let t=yl(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let d={};Object.entries(i).forEach(([p,c])=>{p!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(d[p]=c)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function LC(e,t){let n=Dm(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="${Md(t)}/install.global.js" data-config='${s}'></script>`}function RC(e,t){let n=t?.hooks,o=yl(e),r=o!=="plain",s=Md(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ya(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Fo(a,"theme",e.theme," "),e.launcher&&Fo(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([i,d])=>{a.push(` ${i}: "${d}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,d])=>{typeof d=="string"?a.push(` ${i}: "${d}",`):typeof d=="boolean"&&a.push(` ${i}: ${d},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,d])=>{typeof d=="string"?a.push(` ${i}: "${d}",`):typeof d=="boolean"?a.push(` ${i}: ${d},`):typeof d=="number"&&a.push(` ${i}: ${d},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,d])=>{typeof d=="string"?a.push(` ${i}: "${d}",`):typeof d=="boolean"&&a.push(` ${i}: ${d},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([i,d])=>{a.push(` ${i}: ${d},`)}),a.push(" },")),a.push(...Cl(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{a.push(` "${i}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...bl(e," ")),a.push(...vl(e," ",n)),a.push(...xl(e," ")),a.push(...wl(e," ")),a.push(...Ed(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
|
|
235
|
+
`)}function IC(e,t){let n=t?.hooks,o=Dm(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
|
|
235
236
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
236
|
-
`)};`,""," // Constants",` var CDN_BASE = '${
|
|
237
|
-
`)}var
|
|
237
|
+
`)};`,""," // Constants",` var CDN_BASE = '${Md(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${TC});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Rm}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Rm}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Wm}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Wm}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${ya(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
238
|
+
`)}var Om={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Nm=.1,Fm=.15,_m=1.5,kd=24,$m=40,WC=`
|
|
238
239
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
239
240
|
.persona-dc-root {
|
|
240
241
|
display: flex;
|
|
@@ -385,7 +386,7 @@ ${s.join(`
|
|
|
385
386
|
.persona-dc-stage {
|
|
386
387
|
height: 550px;
|
|
387
388
|
min-height: 400px;
|
|
388
|
-
padding: ${
|
|
389
|
+
padding: ${kd}px;
|
|
389
390
|
overflow: auto;
|
|
390
391
|
background: #f0f1f3;
|
|
391
392
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -475,5 +476,5 @@ ${s.join(`
|
|
|
475
476
|
min-height: 300px;
|
|
476
477
|
}
|
|
477
478
|
}
|
|
478
|
-
`;function
|
|
479
|
+
`;function HC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=WC,document.head.appendChild(e)}function BC(e,t){let n=e.clientWidth-kd*2-$m,o=e.clientHeight-kd*2-$m;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function DC(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function jm(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");HC();let c=Math.max(0,Math.min(o,n.length-1)),u=r,v=s,f=null,b=1,C=!1,E=h("div","persona-dc-root"),L=h("div","persona-dc-toolbar"),W=h("div","persona-dc-toolbar-lead"),A=h("div","persona-dc-toolbar-trail"),k=it({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Se(-1)}),F=h("div");F.style.position="relative";let q=h("button","persona-dc-title-btn");q.type="button",q.setAttribute("aria-expanded","false"),q.setAttribute("aria-haspopup","listbox");let S=h("span","persona-dc-title-text"),V=h("span","persona-dc-title-chevron"),G=re("chevron-down",12,"currentColor",2);G&&V.appendChild(G),q.append(S,V);let oe=h("div","persona-dc-dropdown");oe.setAttribute("role","listbox"),oe.style.display="none";let N=!1;function U(){oe.innerHTML="";for(let ce=0;ce<n.length;ce++){let We=n[ce],ot=h("button","persona-dc-dropdown-item");ot.type="button",ot.setAttribute("role","option"),ot.setAttribute("aria-current",ce===c?"true":"false");let bt=h("span");if(bt.textContent=We.title,ot.appendChild(bt),We.description){let Lt=h("span","persona-dc-dropdown-desc");Lt.textContent=We.description,ot.appendChild(Lt)}ot.addEventListener("click",()=>{he(),Te(ce)}),oe.appendChild(ot)}}function Z(){N=!N,oe.style.display=N?"":"none",q.setAttribute("aria-expanded",N?"true":"false"),N&&U()}function he(){N&&(N=!1,oe.style.display="none",q.setAttribute("aria-expanded","false"))}q.addEventListener("click",ce=>{ce.stopPropagation(),Z()});let ve=()=>he();document.addEventListener("click",ve),F.append(q,oe);let ue=it({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Se(1)}),ne=h("span","persona-dc-counter");W.append(k,F,ue,ne);let fe=null;i&&(fe=to({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ce=>{u=ce,xe.dataset.device=u,f=null,Fe()}}),A.appendChild(fe.element));let te=null;if(a){let ce=h("div","persona-dc-zoom-controls"),We=it({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(Fm,(f??b)-Nm),Fe()}});te=h("span","persona-dc-zoom-level"),te.title="Reset to 100%",te.style.cursor="pointer",te.addEventListener("click",()=>{f=1,Fe()});let ot=it({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(_m,(f??b)+Nm),Fe()}}),bt=it({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,Fe()}});ce.append(We,te,ot,bt),A.appendChild(ce)}if(d){let ce=h("div","persona-dc-separator");A.appendChild(ce);let We=to({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:v,onSelect:ot=>{v=ot,xe.dataset.colorScheme=v,Ae()}});A.appendChild(We.element)}let de=h("div","persona-dc-separator");A.appendChild(de);let Q=it({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});A.appendChild(Q),L.append(W,A);let me=h("div","persona-dc-stage"),xe=h("div","persona-dc-iframe-wrapper");xe.dataset.device=u,xe.dataset.colorScheme=v;let ye=h("iframe","persona-dc-iframe");ye.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ye.setAttribute("loading","lazy"),ye.title=n[c].title,xe.appendChild(ye),me.appendChild(xe),E.append(L,me),e.appendChild(E);function Ae(){try{let ce=ye.contentDocument?.body;if(!ce)return;v==="dark"?ce.classList.add("theme-dark"):ce.classList.remove("theme-dark")}catch{}}ye.addEventListener("load",()=>Ae());function Ee(){let ce=n[c];S.textContent=ce.title,ne.textContent=`${c+1} / ${n.length}`,ye.title=ce.title}function Se(ce){let We=((c+ce)%n.length+n.length)%n.length;Te(We)}function Te(ce){ce<0||ce>=n.length||(c=ce,ye.src=n[c].url,Ee(),p?.(c,n[c]))}function Fe(){if(C)return;let ce=Om[u]??Om.desktop;b=BC(me,ce);let We=Math.max(Fm,Math.min(_m,f??b));DC(xe,ye,ce,We,u),te&&(te.textContent=`${Math.round(We*100)}%`)}let Ue=new ResizeObserver(()=>Fe());Ue.observe(me),Ee(),ye.src=n[c].url,requestAnimationFrame(()=>Fe());function ke(){C||(C=!0,Ue.disconnect(),document.removeEventListener("click",ve),E.remove())}return{element:E,goTo:Te,next:()=>Se(1),prev:()=>Se(-1),getIndex:()=>c,setDevice(ce){u=ce,xe.dataset.device=ce,fe?.setSelected(ce),f=null,Fe()},setColorScheme(ce){v=ce,xe.dataset.colorScheme=ce},setZoom(ce){f=ce,Fe()},destroy:ke}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
|
|
479
480
|
//# sourceMappingURL=index.cjs.map
|