@runtypelabs/persona 4.14.0 → 4.16.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 +520 -21
- package/dist/context-mentions.d.ts +520 -21
- package/dist/context-mentions.js +11 -8
- package/dist/index.cjs +69 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +595 -46
- package/dist/index.d.ts +595 -46
- package/dist/index.global.js +60 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +69 -68
- 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 +520 -21
- package/dist/smart-dom-reader.d.ts +520 -21
- package/dist/testing.cjs +3 -3
- package/dist/testing.d.cts +7 -0
- package/dist/testing.d.ts +7 -0
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +67 -67
- package/dist/theme-editor-preview.d.cts +534 -22
- package/dist/theme-editor-preview.d.ts +534 -22
- package/dist/theme-editor-preview.js +57 -57
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +521 -23
- package/dist/theme-editor.d.ts +521 -23
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +104 -3
- package/dist/theme-reference.d.ts +104 -3
- 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-pane.test.ts +27 -0
- package/src/components/artifact-pane.ts +7 -3
- 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/header-builder.ts +27 -2
- package/src/components/header-layouts.test.ts +56 -0
- package/src/components/header-layouts.ts +29 -9
- package/src/components/launcher-surface.test.ts +403 -0
- package/src/components/launcher.ts +297 -2
- package/src/components/messages.ts +5 -2
- package/src/components/panel.ts +92 -71
- package/src/components/pill-composer-builder.test.ts +18 -0
- package/src/components/suggestions.test.ts +273 -0
- package/src/components/suggestions.ts +528 -86
- package/src/components/welcome.test.ts +121 -0
- package/src/components/welcome.ts +305 -0
- package/src/components/widget-view.test.ts +5 -3
- package/src/components/widget-view.ts +18 -7
- package/src/defaults.ts +7 -5
- package/src/generated/runtype-openapi-contract.ts +17 -0
- package/src/index-core.ts +29 -2
- package/src/launcher-global.ts +11 -8
- package/src/plugins/types.ts +136 -3
- package/src/presets.ts +3 -3
- package/src/session.ts +10 -8
- package/src/styles/widget-styles.test.ts +382 -0
- package/src/styles/widget.css +778 -4
- package/src/suggest-replies-tool.test.ts +233 -2
- package/src/suggest-replies-tool.ts +115 -39
- package/src/testing/mock-stream.test.ts +19 -0
- package/src/testing/mock-stream.ts +20 -0
- 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 +83 -6
- package/src/theme-reference.ts +34 -5
- package/src/types/theme.ts +72 -3
- package/src/types.ts +312 -18
- package/src/ui.body-top-slot.test.ts +95 -0
- package/src/ui.content-width.test.ts +91 -0
- package/src/ui.detached-panel.test.ts +1 -1
- package/src/ui.docked.test.ts +7 -4
- package/src/ui.launcher-teaser.test.ts +162 -0
- package/src/ui.rebuild-composer.test.ts +491 -0
- package/src/ui.render-welcome.test.ts +505 -0
- package/src/ui.scroll-additive.test.ts +91 -21
- package/src/ui.scroll.test.ts +302 -14
- package/src/ui.suggest-replies.test.ts +1112 -1
- package/src/ui.ts +1008 -149
- package/src/ui.welcome.test.ts +504 -0
- package/src/utils/artifact-file.test.ts +1 -1
- package/src/utils/artifact-gate.test.ts +27 -0
- package/src/utils/artifact-gate.ts +9 -0
- package/src/utils/attachment-manager.test.ts +37 -0
- package/src/utils/attachment-manager.ts +15 -0
- package/src/utils/auto-follow.test.ts +23 -0
- package/src/utils/auto-follow.ts +11 -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/config-merge.ts +2 -0
- package/src/utils/content-width.test.ts +37 -0
- package/src/utils/content-width.ts +17 -0
- package/src/utils/icons.test.ts +26 -0
- package/src/utils/icons.ts +8 -0
- package/src/utils/plugin-storage.test.ts +94 -0
- package/src/utils/plugin-storage.ts +98 -0
- package/src/utils/theme.test.ts +216 -0
- package/src/utils/tokens.ts +113 -3
- package/src/welcome.test.ts +213 -0
- package/src/welcome.ts +130 -0
- package/dist/chunk-MMUPR2JW.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
var km=Object.defineProperty;var gr=(e,t)=>()=>(e&&(t=e(e=0)),t);var gl=(e,t)=>{for(var n in t)km(e,n,{get:t[n],enumerable:!0})};var ep={};gl(ep,{DOMPurify:()=>Lm,Marked:()=>Pm});import{Marked as Pm}from"marked";import Lm from"dompurify";var tp=gr(()=>{"use strict"});var xr,Hl=gr(()=>{"use strict";xr=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 Qh(e){return e.replace(/\/+$/,"")}async function Zh(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 ja,nu=gr(()=>{"use strict";Hl();ja=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 xr(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=`${Qh(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 Zh(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 Ua,ou=gr(()=>{"use strict";Ua=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 ru={};gl(ru,{FallbackSpeechEngine:()=>Ua,RuntypeSpeechEngine:()=>ja});var su=gr(()=>{"use strict";nu();ou()});var iu={};gl(iu,{createReconnectController:()=>ty});function ty(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 P of e.getMessages())P.streaming&&(P.streaming=!1,C=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${y?.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 y=e.config.reconnect?.backoffMs??ey,C=e.config.reconnect?.maxAttempts??y.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let P=e.getResumable(),W=P.lastEventId,M=new AbortController;e.setAbortController(M),e.emitReconnect({phase:"resuming",handle:P,attempt:t});let k=null;try{let F=await E({executionId:P.executionId,after:P.lastEventId,signal:M.signal});F&&F.ok&&F.body&&(k=F.body)}catch{k=null}if(M.signal.aborted)return;if(k){let F=e.getMessages().find(w=>w.id===P.assistantMessageId)?.content,z=typeof F=="string"?F:"";try{await e.resumeConnect(k,P.assistantMessageId,z)}catch{}if(M.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:P});return}e.getResumable().lastEventId!==W&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(y[Math.min(t-1,y.length-1)]??1e3),M.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,lu=gr(()=>{"use strict";ey=[1e3,2e3,4e3,8e3,8e3]});import{Marked as Wm}from"marked";import Hm from"dompurify";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:CA,load:Rm,provide:Im,getSync:ml}=mr({fallbackImport:()=>Promise.resolve().then(()=>(tp(),ep))}),Ma=new Set,np=()=>{let e=[...Ma];Ma.clear();for(let t of e)try{t()}catch{}};var op=()=>{let e=ml();return e?Promise.resolve(e):Rm().then(t=>(np(),t))},ls=e=>ml()?()=>{}:(Ma.add(e),op().catch(()=>{}),()=>{Ma.delete(e)}),rp=e=>{Im(e),np()},$n=ml;rp({Marked:Wm,DOMPurify:Hm});var Bm=e=>{if(e)return e},Ea=e=>{let t=null;return n=>{let o=$n();if(!o)return jn(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=Bm(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},hr=e=>e?Ea({markedOptions:e.options,renderer:e.renderer}):Ea(),Dm=Ea(),ap=e=>Dm(e),jn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ip=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),sp=e=>`%%FORM_PLACEHOLDER_${e}%%`,lp=(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=sp(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=sp(t.length);return t.push({token:s,type:r}),s}),n},Om=e=>{let t=hr(e);return n=>{let o=[],r=lp(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="${ip(i)}"></div>`;s=s.replace(d,c)}),s}},Nm=e=>{let t=[],n=lp(e,t),o=ap(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="${ip(s)}"></div>`;o=o.replace(a,d)}),o};var Fm={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"]},_m=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,cp=()=>{let e=null;return t=>{let n=$n();if(!n)return jn(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:")&&!_m.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Fm)}},cs=e=>e===!1?null:typeof e=="function"?e:cp();var dp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,pp=e=>e.includes("|"),up=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())},$m=e=>`| ${e.join(" | ")} |`,jm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Um=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fp=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
|
+
var fy=Object.defineProperty;var Nr=(e,t)=>()=>(e&&(t=e(e=0)),t);var oc=(e,t)=>{for(var n in t)fy(e,n,{get:t[n],enumerable:!0})};var bu={};oc(bu,{DOMPurify:()=>hy,Marked:()=>my});import{Marked as my}from"marked";import hy from"dompurify";var vu=Nr(()=>{"use strict"});var qr,Ac=Nr(()=>{"use strict";qr=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 Fb(e){return e.replace(/\/+$/,"")}async function _b(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,xg=Nr(()=>{"use strict";Ac();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 qr(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=`${Fb(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 _b(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var gi,Cg=Nr(()=>{"use strict";gi=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 wg={};oc(wg,{FallbackSpeechEngine:()=>gi,RuntypeSpeechEngine:()=>ui});var Ag=Nr(()=>{"use strict";xg();Cg()});var Tg={};oc(Tg,{createReconnectController:()=>jb});function jb(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let x=n;n=null,x()}},a=()=>{let x=e.getStatus();x!=="resuming"&&x!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},g=x=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},x)}),b=()=>{let x=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let M of e.getMessages())M.streaming&&(M.streaming=!1,C=!0);let S=e.buildErrorContent("Connection lost and the response could not be resumed.");S?e.appendMessage({id:`reconnect-failed-${x?.executionId??e.nextSequence()}`,role:"assistant",content:S,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 x=e.config.reconnect?.backoffMs??$b,C=e.config.reconnect?.maxAttempts??x.length,S=e.config.reconnectStream;if(!S){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let M=e.getResumable(),P=M.lastEventId,T=new AbortController;e.setAbortController(T),e.emitReconnect({phase:"resuming",handle:M,attempt:t});let L=null;try{let H=await S({executionId:M.executionId,after:M.lastEventId,signal:T.signal});H&&H.ok&&H.body&&(L=H.body)}catch{L=null}if(T.signal.aborted)return;if(L){let H=e.getMessages().find(_=>_.id===M.assistantMessageId)?.content,O=typeof H=="string"?H:"";try{await e.resumeConnect(L,M.assistantMessageId,O)}catch{}if(T.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:M});return}e.getResumable().lastEventId!==P&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await g(x[Math.min(t-1,x.length-1)]??1e3),T.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var $b,Eg=Nr(()=>{"use strict";$b=[1e3,2e3,4e3,8e3,8e3]});import{Marked as vy}from"marked";import xy from"dompurify";var Fr=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(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:LT,load:yy,provide:by,getSync:rc}=Fr({fallbackImport:()=>Promise.resolve().then(()=>(vu(),bu))}),Xa=new Set,xu=()=>{let e=[...Xa];Xa.clear();for(let t of e)try{t()}catch{}};var Cu=()=>{let e=rc();return e?Promise.resolve(e):yy().then(t=>(xu(),t))},Ds=e=>rc()?()=>{}:(Xa.add(e),Cu().catch(()=>{}),()=>{Xa.delete(e)}),wu=e=>{by(e),xu()},Zn=rc;wu({Marked:vy,DOMPurify:xy});var Cy=e=>{if(e)return e},Qa=e=>{let t=null;return n=>{let o=Zn();if(!o)return eo(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=Cy(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},_r=e=>e?Qa({markedOptions:e.options,renderer:e.renderer}):Qa(),wy=Qa(),Su=e=>wy(e),eo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Tu=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Au=e=>`%%FORM_PLACEHOLDER_${e}%%`,Eu=(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},Ay=e=>{let t=_r(e);return n=>{let o=[],r=Eu(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${Tu(i)}"></div>`;s=s.replace(p,c)}),s}},Sy=e=>{let t=[],n=Eu(e,t),o=Su(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Tu(s)}"></div>`;o=o.replace(a,p)}),o};var Ty={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Ey=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Mu=()=>{let e=null;return t=>{let n=Zn();if(!n)return eo(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:")&&!Ey.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Ty)}},Os=e=>e===!1?null:typeof e=="function"?e:Mu();var ku=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Lu=e=>e.includes("|"),Pu=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())},My=e=>`| ${e.join(" | ")} |`,ky=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Ly=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ru=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(!Lu(r)||ku.test(r)||!ku.test(s))continue;let a=Pu(r).length;if(a<1)continue;let i=ky(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Lu(d))break;let c=My(Ly(Pu(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
|
|
3
|
+
`):e};var Iu="var(--persona-md-table-scroll-fade, 24px)",Wu=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 Hu(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":Iu),e.style.setProperty("--persona-fade-r",r<=1?"0px":Iu)}function sc(e){Wu.has(e)||(Wu.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Hu(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Hu)}var Dn="webmcp:",ac=new Map,Du=e=>{ac.clear();for(let t of e){let n=t.title?.trim();n&&ac.set(t.name,n)}},Fs=e=>ac.get(ic(e)),Za={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ou=null;function Fu(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}:${Py(t.join(""))}`}function Nu(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 Py(e){let t=Nu(e,0).toString(36),n=Nu(e,2654435761).toString(36);return`${t}.${n}`}var Ns=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 Za.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Du(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=Iy(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Rn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let x=typeof document<"u"&&!!document.modelContext;return Rn(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=ic(t),a;try{a=await r.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return Rn(`Failed to read WebMCP registry: ${C}`)}Du(a);let i=a.find(x=>x.name===s);if(!i)return Rn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Rn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Rn("Aborted by cancel()");let p=Fs(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Rn("User declined the tool call.");if(o?.aborted)return Rn("Aborted by cancel()");let c=new AbortController,g=!1,b=setTimeout(()=>{g=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let x=await r.executeTool(i,Dy(n),{signal:c.signal});return Wy(x)}catch(x){if(g)return Rn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Rn("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return Rn(C)}finally{clearTimeout(b),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}(Ou?await Ou():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Za.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,Za.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??Hy;try{return await n(t)}catch(o){return Za.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=>Ry(t,o))}},ic=e=>e.startsWith(Dn)?e.slice(Dn.length):e,or=e=>e.startsWith(Dn),Ry=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Iy=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Wy=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:Oy(t)}]}},Rn=e=>({isError:!0,content:[{type:"text",text:e}]}),Hy=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=By(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)},Jm=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)}},Xm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ym=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function rn(e){return e==="card"?"collapsed":e}function _o(e){return e.split(";",1)[0].trim().toLowerCase()}function Qm(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(_o(r)===t)return{mode:rn(s),selector:_o(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(_o(r)===o)return{mode:rn(s),selector:o}}function wp(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:rn(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?_o(t.file.mimeType):void 0,d=i?Qm(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:rn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:rn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:rn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:rn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:rn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Un(e,t){return wp(e,t).mode}function us(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 Zm="agent_",eh="flow_";function Ap(e){return e.startsWith(Zm)?{kind:"agentId",agentId:e}:e.startsWith(eh)?{kind:"flowId",flowId:e}:null}function Sp(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=Ap(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=Ap(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.`)}import{parse as th,ARR as nh,OBJ as oh,STR as rh}from"partial-json";var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Tp=()=>document.createDocumentFragment(),Ne=(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},zn=(...e)=>e.filter(Boolean).join(" ");var Pa="ask_user_question",fs=8,yr="data-persona-ask-sheet-for",sh="Other",ah="Other\u2026",Ep="Type your own answer here",kp="Send",ih="Next",lh="Back",ch="Submit all",dh="Skip",ph=3,vl="data-ask-current-index",xl="data-ask-question-count",Pp="data-ask-answers",Cl="data-ask-grouped",Lp="data-ask-layout",uh=e=>e.layout==="pills"?"pills":"rows",fh=e=>e.getAttribute(Lp)==="pills"?"pills":"rows",Mp=!1,Rp=e=>e.replace(/["\\]/g,"\\$&"),io=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Pa,La=e=>e?.features?.askUserQuestion??{},lo=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=th(r,rh|oh|nh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},gs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>fs&&!Mp&&(Mp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${fs}.`)),t.slice(0,fs)},gh=e=>gs(e)[0]??null,mh=(e,t)=>gs(e)[t]??null,Ip=(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))},Wp=(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},hh=(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=Wp(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},yh=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},bh=(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<ph;c++)s.appendChild(yh(o));return s}if(d.forEach((c,u)=>{s.appendChild(hh(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?sh:ah;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??Ep,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(f),u.appendChild(b);let y=Wp(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},Hp=(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??Ep,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??kp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},vh=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??kp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},xh=(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??lh,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??dh,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??ch:n.nextLabel??ih,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},$o=e=>{let t=e.getAttribute(Pp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Bp=(e,t)=>{e.setAttribute(Pp,JSON.stringify(t))},gn=e=>{let t=Number(e.getAttribute(vl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ch=(e,t)=>{e.setAttribute(vl,String(Math.max(0,Math.floor(t))))},br=e=>{let t=Number(e.getAttribute(xl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},co=e=>e.getAttribute(Cl)==="true",wh=(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},Ah=(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)))},Ra=(e,t)=>{let{payload:n}=lo(t),o=gs(n),r=$o(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},Dp=e=>{let t=$o(e),n=gn(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="")},Op=e=>{if(!co(e))return;let t=$o(e),n=gn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},wl=(e,t,n)=>{let o=La(n),r=fh(e),{payload:s,complete:a}=lo(t),i=co(e),d=gn(e),p=br(e),c=i?mh(s,d):gh(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 W=typeof c?.question=="string"?c.question:"";y.textContent=W,y.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let W=bh(c,o,a,r);C.replaceWith(W)}if(r!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(Hp(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(vh(o)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=xh(d,p,o);P?P.replaceWith(W):e.appendChild(W)}else P&&P.remove();Dp(e),Op(e)},Sh=(e,t,n)=>{let o=La(t),r=uh(o),s=e.toolCall.id,a=gs(n),i=Math.max(1,a.length),d=i>1,p=wh(e,a),c=d?Ah(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(yr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(xl,String(i)),u.setAttribute(vl,String(c)),u.setAttribute(Cl,d?"true":"false"),u.setAttribute(Lp,r),Bp(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`),Ip(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 E=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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(Hp(o,r)),wl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Th=(e,t,n)=>{let{payload:o}=lo(t),r=Math.max(1,gs(o).length);r>br(e)&&(e.setAttribute(xl,String(r)),r>1&&!co(e)&&e.setAttribute(Cl,"true")),wl(e,t,n)},Mh=(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=La(t);Ip(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=lo(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},ms=(e,t,n)=>{if(!n||!io(e)||La(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${yr}]`).forEach(p=>{p.getAttribute(yr)!==r&&p.remove()});let a=n.querySelector(`[${yr}="${Rp(r)}"]`);if(a){Th(a,e,t);return}let{payload:i}=lo(e),d=Sh(e,t,i);n.appendChild(d)},jo=(e,t)=>{if(!e)return;let n=t?`[${yr}="${Rp(t)}"]`:`[${yr}]`;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)})},Al=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),po=(e,t)=>{let n=$o(e),o=gn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Bp(e,n),Dp(e),Op(e)},Ia=(e,t,n,o)=>{let r=br(e),s=Math.max(0,Math.min(r-1,o));Ch(e,s),wl(e,t,n)};var kn="suggest_replies";var Np={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},Sl={name:kn,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:Np,origin:"sdk",annotations:{readOnlyHint:!0}},Tl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Wa=e=>e.variant==="tool"&&e.toolCall?.name===kn,Fp=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},Ml=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Wa(n))continue;let o=Fp(n.toolCall?.args);return o.length>0?o:null}return null},_p=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var $p={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:fs,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},jp={name:Pa,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:$p,origin:"sdk",annotations:{readOnlyHint:!0}},hs=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(jp),_p(e)&&t.push(Sl),t};import{parse as Up,STR as zp,OBJ as qp}from"partial-json";var Ha=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},By=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)}},Dy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Oy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function ln(e){return e==="card"?"collapsed":e}function rr(e){return e.split(";",1)[0].trim().toLowerCase()}function Ny(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(rr(r)===t)return{mode:ln(s),selector:rr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(rr(r)===o)return{mode:ln(s),selector:o}}function _u(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:ln(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?rr(t.file.mimeType):void 0,p=i?Ny(o.files.byMediaType,i):void 0;if(i&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:i,selector:p.selector}};if(o.files.default)return{mode:ln(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:ln(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:ln(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:ln(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:ln(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function to(e,t){return _u(e,t).mode}function _s(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 Fy="agent_",_y="flow_";function $u(e){return e.startsWith(Fy)?{kind:"agentId",agentId:e}:e.startsWith(_y)?{kind:"flowId",flowId:e}:null}function ju(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=$u(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=$u(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.`)}import{parse as $y,ARR as jy,OBJ as Uy,STR as zy}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Uu=()=>document.createDocumentFragment(),Me=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},In=(...e)=>e.filter(Boolean).join(" ");var ei="ask_user_question",$s=8,$r="data-persona-ask-sheet-for",qy="Other",Vy="Other\u2026",qu="Type your own answer here",Vu="Send",Ky="Next",Gy="Back",Jy="Submit all",Yy="Skip",Xy=3,lc="data-ask-current-index",cc="data-ask-question-count",Ku="data-ask-answers",dc="data-ask-grouped",Gu="data-ask-layout",Qy=e=>e.layout==="pills"?"pills":"rows",Zy=e=>e.getAttribute(Gu)==="pills"?"pills":"rows",zu=!1,Ju=e=>e.replace(/["\\]/g,"\\$&"),vo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ei,ti=e=>e?.features?.askUserQuestion??{},xo=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=$y(r,zy|Uy|jy);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},js=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>$s&&!zu&&(zu=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${$s}.`)),t.slice(0,$s)},eb=e=>js(e)[0]??null,tb=(e,t)=>js(e)[t]??null,Yu=(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))},Xu=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},nb=(e,t,n,o)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",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=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Xu(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ob=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},rb=(e,t,n,o)=>{let s=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Xy;c++)s.appendChild(ob(o));return s}if(p.forEach((c,g)=>{s.appendChild(nb(c,g,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?qy:Vy;if(o==="rows"){let g=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(p.length)),g.setAttribute("data-ask-other-row","true");let b=y("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??qu,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(f),g.appendChild(b);let x=Xu(o,a,p.length);x&&g.appendChild(x),s.appendChild(g)}else{let g=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??c,s.appendChild(g)}}return s},Qu=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");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??qu,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Vu,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},sb=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Vu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ab=(e,t,n)=>{let o=y("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=y("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=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Yy,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Jy:n.nextLabel??Ky,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},sr=e=>{let t=e.getAttribute(Ku);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zu=(e,t)=>{e.setAttribute(Ku,JSON.stringify(t))},vn=e=>{let t=Number(e.getAttribute(lc)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ib=(e,t)=>{e.setAttribute(lc,String(Math.max(0,Math.floor(t))))},jr=e=>{let t=Number(e.getAttribute(cc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Co=e=>e.getAttribute(dc)==="true",lb=(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},cb=(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)))},ni=(e,t)=>{let{payload:n}=xo(t),o=js(n),r=sr(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},eg=e=>{let t=sr(e),n=vn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},tg=e=>{if(!Co(e))return;let t=sr(e),n=vn(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}},pc=(e,t,n)=>{let o=ti(n),r=Zy(e),{payload:s,complete:a}=xo(t),i=Co(e),p=vn(e),d=jr(e),c=i?tb(s,p):eb(s),g=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let P=typeof c?.question=="string"?c.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let P=rb(c,o,a,r);C.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Qu(o,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!S?e.appendChild(sb(o)):(!g||i)&&S&&S.remove(),e.setAttribute("data-multi-select",g?"true":"false");let M=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=ab(p,d,o);M?M.replaceWith(P):e.appendChild(P)}else M&&M.remove();eg(e),tg(e)},db=(e,t,n)=>{let o=ti(t),r=Qy(o),s=e.toolCall.id,a=js(n),i=Math.max(1,a.length),p=i>1,d=lb(e,a),c=p?cb(e,i):0,g=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute($r,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(cc,String(i)),g.setAttribute(lc,String(c)),g.setAttribute(dc,p?"true":"false"),g.setAttribute(Gu,r),Zu(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Yu(g,o);let b=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",b.appendChild(x),g.appendChild(b);let S=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),g.appendChild(S),r!=="rows"&&g.appendChild(Qu(o,r)),pc(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},pb=(e,t,n)=>{let{payload:o}=xo(t),r=Math.max(1,js(o).length);r>jr(e)&&(e.setAttribute(cc,String(r)),r>1&&!Co(e)&&e.setAttribute(dc,"true")),pc(e,t,n)},ub=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=ti(t);Yu(n,o);let r=y("span","persona-ask-stub-label"),{complete:s}=xo(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Us=(e,t,n)=>{if(!n||!vo(e)||ti(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${$r}]`).forEach(d=>{d.getAttribute($r)!==r&&d.remove()});let a=n.querySelector(`[${$r}="${Ju(r)}"]`);if(a){pb(a,e,t);return}let{payload:i}=xo(e),p=db(e,t,i);n.appendChild(p)},ar=(e,t)=>{if(!e)return;let n=t?`[${$r}="${Ju(t)}"]`:`[${$r}]`;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)})},uc=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),wo=(e,t)=>{let n=sr(e),o=vn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Zu(e,n),eg(e),tg(e)},oi=(e,t,n,o)=>{let r=jr(e),s=Math.max(0,Math.min(r-1,o));ib(e,s),pc(e,t,n)};var On="suggest_replies";var og={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},gc={name:On,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:og,origin:"sdk",annotations:{readOnlyHint:!0}},fc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ur=e=>e.variant==="tool"&&e.toolCall?.name===On,rg=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},mc=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ur(n))continue;let o=rg(n.toolCall?.args);return o.length>0?o:null}return null},ng=new Set,gb=(e,t,n)=>{let o=`${e}:${t}:${n}`;ng.has(o)||(ng.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Ao=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let i=t?.[a],p=n?.[a];i===void 0||p===void 0||i!==p&&gb(a,p,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 sg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:$s,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},ag={name:ei,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:sg,origin:"sdk",annotations:{readOnlyHint:!0}},zs=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(ag),Ao(e).expose&&t.push(gc),t};import{parse as ig,STR as lg,OBJ as cg}from"partial-json";var ri=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),So=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)}},fb=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`},dg=e=>e.status==="complete"?fb(e):e.status==="pending"?"Waiting":"",mb=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 pg=e=>e.status==="complete"?mb(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`},Vs=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)},hc=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Vs(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&&qs(o,n.slice(s,a.index),[]),a[1]!==void 0?qs(o,a[1],["bold"]):a[2]!==void 0?qs(o,a[2],["italic"]):a[3]!==void 0&&qs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&qs(o,n.slice(s),[]),o},qs=(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})},hb=()=>{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()=>{}}},vs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},kl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Pl=()=>{let e=Ph();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)}},Ll=()=>{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=Up(n,zp|qp);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ha(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ha(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Lh=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ha(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ha(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=Up(s,zp|qp),d=r(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Rl=()=>{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 Gp="4.14.0";var fo=Gp;var Ih="https://api.runtype.com/v1/dispatch",Na="https://api.runtype.com";function Wh(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 Il=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 Hh(e){switch(e){case"json":return Ll;case"regex-json":return Pl;case"xml":return Rl;default:return kl}}var Jp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(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=Jp(n);if(!Jp(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=vs(e);return vs(t)!==null&&a===null?t:e}var vr=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??Ih,this.headers={"Content-Type":"application/json","X-Persona-Version":fo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Hh(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 ds(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=Sp(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$/,"")||Na}/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":fo},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$/,"")||Na}/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":fo},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(Il).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":fo},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$/,"")||Na}/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?Cp(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(/\/+$/,"")||Na}/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=[...hs(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(Il).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=[...hs(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(Il).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=[...hs(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=S=>{let O=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,v=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,R=S.tools?S.tools.map(T=>({...T,chunks:T.chunks?[...T.chunks]:void 0})):void 0;return{...S,reasoning:O,toolCall:v,tools:R}},b=S=>{if(S.role!=="assistant"||S.variant)return!0;let O=Array.isArray(S.contentParts)&&S.contentParts.length>0,v=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||O||v||!!S.stopReason},f=S=>{b(S)&&n({type:"message",message:u(S)})},y=null,C=null,E={current:null},P={current:null},W=null,M="",k=new Map,F=new Map,z=new Map,w=new Map,U=new Map,q={lastId:null,byStep:new Map},ee={lastId:null,byCall:new Map},D=S=>{if(S==null)return null;try{return String(S)}catch{return null}},$=S=>D(S.stepId??S.step_id??S.step??S.parentId??S.flowStepId??S.flow_step_id),X=S=>D(S.callId??S.call_id??S.requestId??S.request_id??S.toolCallId??S.tool_call_id??S.stepId??S.step_id),ye=o,be=!1,He=()=>{if(y)return y;let S,O="",v=W;return!be&&ye?(S=ye,be=!0,O=r??""):ye&&v?S=`${ye}_${v}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:S,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(y),y},re=(S,O)=>{q.lastId=O,S&&q.byStep.set(S,O)},me=(S,O)=>{let v=S.reasoningId??S.id,R=$(S);if(v){let I=String(v);return re(R,I),I}if(R){let I=q.byStep.get(R);if(I)return q.lastId=I,I}if(q.lastId&&!O)return q.lastId;if(!O)return null;let T=`reason-${c()}`;return re(R,T),T},Z=S=>{let O=w.get(S);if(O)return O;let v={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:S,status:"streaming",chunks:[]}};return w.set(S,v),f(v),v},ce=(S,O)=>{ee.lastId=O,S&&ee.byCall.set(S,O)},Q=new Set,pe=new Map,ve=new Set,he=new Map,Ae=S=>{if(!S)return!1;let O=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return O==="emit_artifact_markdown"||O==="emit_artifact_component"},at=(S,O)=>{let v=S.toolId??S.id,R=X(S);if(v){let I=String(v);return ce(R,I),I}if(R){let I=ee.byCall.get(R);if(I)return ee.lastId=I,I}if(ee.lastId&&!O)return ee.lastId;if(!O)return null;let T=`tool-${c()}`;return ce(R,T),T},Me=S=>{let O=U.get(S);if(O)return O;let v={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:S,status:"pending"}};return U.set(S,v),f(v),v},Be=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let O=Number(S);if(!Number.isNaN(O)&&Number.isFinite(O))return O;let v=Date.parse(S);if(!Number.isNaN(v))return v}return Date.now()},Oe=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},ze=new Map,Te=new Map,le=new Map,Pe=(S,O,v)=>{let R=le.get(S);R||(R=[],le.set(S,R));let T=0,I=R.length;for(;T<I;){let B=T+I>>>1;R[B].seq<O?T=B+1:I=B}R[T]?.seq===O?R[T]={seq:O,text:v}:R.splice(T,0,{seq:O,text:v});let K="";for(let B=0;B<R.length;B++)K+=R[B].text;return K},rt=(S,O)=>{let v=Oe(O),R=Te.get(S.id),T=Bh(R,v);S.rawContent=T;let I=ze.get(S.id),K=Ie=>{let Xe=S.content??"";Ie.trim()!==""&&(Xe.trim().length===0||Ie.startsWith(Xe)||Ie.trimStart().startsWith(Xe.trim()))&&(S.content=Ie)},B=()=>{if(I){let Ie=I.close?.();Ie instanceof Promise&&Ie.catch(()=>{})}ze.delete(S.id),Te.delete(S.id),S.streaming=!1,f(S)};if(!I){K(v),B();return}let j=vs(T);if(j!==null&&j.trim()!==""){K(j),B();return}let Y=Ie=>{let Xe=typeof Ie=="string"?Ie:Ie?.text??null;if(Xe!==null&&Xe.trim()!=="")return Xe;let ot=I.getExtractedText();return ot!==null&&ot.trim()!==""?ot:v},Ke;try{Ke=I.processChunk(T)}catch{K(v),B();return}if(Ke instanceof Promise){Ke.then(Ie=>{K(Y(Ie)),B()}).catch(()=>{K(v),B()});return}K(Y(Ke)),B()},vt=null,kt=(S,O,v,R)=>{S.rawContent=O,ze.has(S.id)||ze.set(S.id,this.createStreamParser());let T=ze.get(S.id),I=O.trim().startsWith("{")||O.trim().startsWith("[");if(I&&Te.set(S.id,O),T.__isPlainTextParser===!0){S.content=R!==void 0?O:S.content+v,Te.delete(S.id),ze.delete(S.id),S.rawContent=void 0,f(S);return}let B=T.processChunk(O);if(B instanceof Promise)B.then(j=>{let Y=typeof j=="string"?j:j?.text??null;Y!==null&&Y.trim()!==""?(S.content=Y,f(S)):!I&&!O.trim().startsWith("<")&&(S.content=R!==void 0?O:S.content+v,Te.delete(S.id),ze.delete(S.id),S.rawContent=void 0,f(S))}).catch(()=>{S.content=R!==void 0?O:S.content+v,Te.delete(S.id),ze.delete(S.id),S.rawContent=void 0,f(S)});else{let j=typeof B=="string"?B:B?.text??null;j!==null&&j.trim()!==""?(S.content=j,f(S)):!I&&!O.trim().startsWith("<")&&(S.content=R!==void 0?O:S.content+v,Te.delete(S.id),ze.delete(S.id),S.rawContent=void 0,f(S))}},St=(S,O)=>{let v=O??S.content;if(v==null||v===""){S.streaming=!1,f(S);return}let T=Te.get(S.id)??Oe(v);S.rawContent=T;let I=ze.get(S.id),K=null,B=!1;if(I&&(K=I.getExtractedText(),K===null&&(K=vs(T)),K===null)){let j=I.processChunk(T);j instanceof Promise?(B=!0,j.then(Y=>{let Ke=typeof Y=="string"?Y:Y?.text??null;Ke!==null&&(S.content=Ke,S.streaming=!1,ze.delete(S.id),Te.delete(S.id),f(S))}).catch(()=>{})):K=typeof j=="string"?j:j?.text??null}if(!B){K!==null&&K.trim()!==""?S.content=K:Te.has(S.id)||(S.content=Oe(v));let j=ze.get(S.id);if(j){let Y=j.close?.();Y instanceof Promise&&Y.catch(()=>{}),ze.delete(S.id)}Te.delete(S.id),S.streaming=!1,f(S)}},De=(S,O,v)=>{let R=F.get(S);if(R)return R;let T={id:`nested-${O}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:O}};return F.set(S,T),f(T),T},de=[],Ze,Re=new Map,fe=0,ae="agent",Le=!1,it=null,ue=null,we=new Map,te=this.config.iterationDisplay??"separate";for(Ze=()=>{for(let S=0;S<de.length;S++){let O=de[S].payloadType,v=de[S].payload;if(!Le&&ae!=="flow"&&typeof v.stepType=="string"&&(ae="flow"),O==="reasoning_start"){let R=typeof v.id=="string"?v.id:null,T=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(R&&T){k.set(R,T),De(R,T,"reasoning");continue}let I=me(v,!0)??`reason-${c()}`,K=Z(I);K.reasoning=K.reasoning??{id:I,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Be(v.startedAt??v.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(O==="reasoning_delta"){let R=typeof v.id=="string"?v.id:null;if(R&&k.has(R)&&F.has(R)){let B=F.get(R),j=v.reasoningText??v.text??v.delta??"";j&&v.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(j)),f(B));continue}let T=me(v,!1)??me(v,!0)??`reason-${c()}`,I=Z(T);I.reasoning=I.reasoning??{id:T,status:"streaming",chunks:[]},I.reasoning.startedAt=I.reasoning.startedAt??Be(v.startedAt??v.timestamp);let K=v.reasoningText??v.text??v.delta??"";if(K&&v.hidden!==!0){let B=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(B!==void 0){let j=Pe(T,B,String(K));I.reasoning.chunks=[j]}else I.reasoning.chunks.push(String(K))}if(I.reasoning.status=v.done?"complete":"streaming",v.done){I.reasoning.completedAt=Be(v.completedAt??v.timestamp);let B=I.reasoning.startedAt??Date.now();I.reasoning.durationMs=Math.max(0,(I.reasoning.completedAt??Date.now())-B)}I.streaming=I.reasoning.status!=="complete",f(I)}else if(O==="reasoning_complete"){let R=typeof v.id=="string"?v.id:null;if(R&&k.has(R)&&F.has(R)){let j=F.get(R);if(j.reasoning){let Y=typeof v.text=="string"?v.text:"";Y&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(Y),j.reasoning.status="complete",j.streaming=!1,f(j)}k.delete(R),F.delete(R);continue}let T=me(v,!1)??me(v,!0)??`reason-${c()}`,I=typeof v.text=="string"?v.text:"";!w.get(T)&&(I||v.scope==="loop")&&Z(T);let K=w.get(T);if(K?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),I&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(I),K.reasoning.status="complete",K.reasoning.completedAt=Be(v.completedAt??v.timestamp);let j=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-j),K.streaming=!1,f(K)}let B=$(v);B&&q.byStep.delete(B)}else if(O==="tool_start"){y&&(y.streaming=!1,f(y),y=null),typeof v.iteration=="number"&&(fe=v.iteration);let R=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??at(v,!0)??`tool-${c()}`,T=v.toolName??v.name;if(Ae(T)){Q.add(R);continue}ce(X(v),R);let I=Me(R),K=I.toolCall??{id:R,status:"pending"};K.name=T??K.name,K.status="running",v.parameters!==void 0?K.args=v.parameters:v.args!==void 0&&(K.args=v.args),K.startedAt=K.startedAt??Be(v.startedAt??v.timestamp),K.completedAt=void 0,K.durationMs=void 0,I.toolCall=K,I.streaming=!0,v.executionId&&(I.agentMetadata={executionId:v.executionId,iteration:v.iteration}),f(I)}else if(O==="tool_output_delta"){let R=at(v,!1)??at(v,!0)??`tool-${c()}`;if(Q.has(R))continue;let T=Me(R),I=T.toolCall??{id:R,status:"running"};I.startedAt=I.startedAt??Be(v.startedAt??v.timestamp);let K=v.text??v.delta??v.message??"";K&&(I.chunks=I.chunks??[],I.chunks.push(String(K))),I.status="running",T.toolCall=I,T.streaming=!0;let B=v.agentContext;(B||v.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),f(T)}else if(O==="tool_complete"){let R=at(v,!1)??at(v,!0)??`tool-${c()}`;if(Q.has(R)){Q.delete(R);continue}let T=Me(R),I=T.toolCall??{id:R,status:"running"};I.status="complete",v.result!==void 0&&(I.result=v.result),typeof v.duration=="number"&&(I.duration=v.duration),I.completedAt=Be(v.completedAt??v.timestamp);let K=v.duration??v.executionTime;if(typeof K=="number")I.durationMs=K;else{let Y=I.startedAt??Date.now();I.durationMs=Math.max(0,(I.completedAt??Date.now())-Y)}T.toolCall=I,T.streaming=!1;let B=v.agentContext;(B||v.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),f(T);let j=X(v);j&&ee.byCall.delete(j)}else if(O==="await"&&v.toolName){let R=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,T=R??v.toolId??`local-${c()}`,I=Me(T),K=v.toolName,B=v.origin==="webmcp"&&!Fo(K)?`webmcp:${K}`:K,j=Fo(B),Y=I.toolCall??{id:T,status:"pending"};Y.name=B,Y.args=v.parameters,Y.status=j?"running":"complete",Y.chunks=Y.chunks??[],Y.startedAt=Y.startedAt??Be(v.startedAt??v.timestamp??v.awaitedAt),j?(Y.completedAt=void 0,Y.duration=void 0,Y.durationMs=void 0):Y.completedAt=Y.completedAt??Y.startedAt,I.toolCall=Y,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:v.executionId??I.agentMetadata?.executionId,awaitingLocalTool:!0,...R?{webMcpToolCallId:R}:{}},f(I)}else if(O==="text_start"){let R=typeof v.id=="string"?v.id:null,T=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(R&&T){k.set(R,T);continue}let I=y;I&&(ae==="flow"?(St(I),vt=I):(I.streaming=!1,f(I)),y=null),W=typeof v.id=="string"?v.id:W,M=""}else if(O==="text_delta"){let R=typeof v.id=="string"?v.id:null,T=R?k.get(R):void 0;if(R&&T){let K=typeof v.delta=="string"?v.delta:"",B=(z.get(R)??"")+K;if(z.set(R,B),B.trim()==="")continue;let j=De(R,T);j.agentMetadata={...j.agentMetadata,executionId:v.executionId,parentToolId:T},kt(j,B,K,void 0);continue}if(W=typeof v.id=="string"?v.id:W,ae==="flow"){let K=typeof v.delta=="string"?v.delta:"";if(M+=K,M.trim()==="")continue;let B=He();B.agentMetadata={executionId:v.executionId,iteration:v.iteration},kt(B,M,K,void 0),C=B;continue}let I=He();I.content+=v.delta??"",I.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:it??void 0,agentName:ue?.agentName},C=I,f(I)}else if(O==="text_complete"){let R=typeof v.id=="string"?v.id:null;if(R&&k.has(R)){let I=F.get(R);I&&St(I),k.delete(R),z.delete(R),F.delete(R);continue}let T=y;T&&(ae==="flow"?(St(T),vt=T):((T.content??"")===""&&typeof v.text=="string"&&(T.content=v.text),T.streaming=!1,f(T)),y=null),W=null,M=""}else if(O==="step_complete"){let R=v.stepType,T=v.executionType;if(R==="tool"||T==="context")continue;if(v.success===!1){let I=v.error,K=typeof I=="string"&&I!==""?I:I!=null&&typeof I=="object"&&Reflect.has(I,"message")?String(I.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let B=y;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"});continue}{let I=vt;vt=null;let K=v.stopReason,B=v.result?.response;if(I)K&&(I.stopReason=K),B!=null?rt(I,B):I.streaming!==!1&&(ze.delete(I.id),Te.delete(I.id),I.streaming=!1,f(I));else{let j=B!=null&&B!=="";if(j||K){let Y=He();K&&(Y.stopReason=K),j?St(Y,B):(Y.streaming=!1,f(Y))}}continue}}else if(O==="execution_start")ae=v.kind==="flow"?"flow":"agent",Le=!0,ae==="agent"&&(ue={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Be(v.startedAt)});else if(O==="turn_start"){let R=typeof v.iteration=="number"?v.iteration:fe;if(R!==fe){if(ue&&(ue.currentIteration=R),te==="separate"&&R>1){let T=y;T&&(T.streaming=!1,f(T),we.set(R-1,T),y=null)}fe=R}it=typeof v.id=="string"?v.id:null,C=null}else if(O==="tool_input_delta"){let R=v.toolCallId??ee.lastId;if(R){let T=U.get(R);T?.toolCall&&(T.toolCall.chunks=T.toolCall.chunks??[],T.toolCall.chunks.push(v.delta??""),f(T))}}else{if(O==="tool_input_complete")continue;if(O==="turn_complete"){let R=v.stopReason,T=y??C;if(R&&T!==null){let I=v.id;(!I||T.agentMetadata?.turnId===I)&&(T.stopReason=R,f(T))}it===v.id&&(it=null)}else if(O==="media_start"){let R=String(v.id);Re.set(R,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(O==="media_delta"){let R=Re.get(String(v.id));R&&typeof v.delta=="string"&&R.parts.push(v.delta)}else if(O==="media_complete"){let R=String(v.id),T=Re.get(R);Re.delete(R);let I=(typeof v.mediaType=="string"?v.mediaType:void 0)??T?.mediaType??"application/octet-stream",K=typeof v.data=="string"?v.data:void 0,B=typeof v.url=="string"?v.url:T&&T.parts.length>0?T.parts.join(""):void 0,j=null;if(K)j={type:"media",data:K,mediaType:I};else if(B){let Xe=I.toLowerCase();j={type:Xe==="image"||Xe.startsWith("image/")?"image-url":"file-url",url:B,mediaType:I}}let Y=v.toolCallId??T?.toolCallId,Ke=j?[j]:[],Ie=[];for(let Xe of Ke){if(!Xe||typeof Xe!="object")continue;let ot=Xe,V=typeof ot.type=="string"?ot.type:void 0,je=typeof ot.mediaType=="string"?ot.mediaType.toLowerCase():"",xe=null,Ue="";if(V==="media"){let Fe=typeof ot.data=="string"?ot.data:void 0;if(!Fe)continue;Ue=je.length>0?je:"application/octet-stream",xe=`data:${Ue};base64,${Fe}`}else if(V==="image-url"){let Fe=typeof ot.url=="string"?ot.url:void 0;if(!Fe)continue;Ue=je,xe=Fe}else if(V==="file-url"){let Fe=typeof ot.url=="string"?ot.url:void 0;if(!Fe)continue;Ue=je,xe=Fe}else continue;if(xe)if(V==="image-url"||Ue.startsWith("image/"))Ie.push({type:"image",image:xe,...Ue.includes("/")?{mimeType:Ue}:{}});else if(Ue.startsWith("audio/"))Ie.push({type:"audio",audio:xe,mimeType:Ue});else if(Ue.startsWith("video/"))Ie.push({type:"video",video:xe,mimeType:Ue});else{let Fe=Ue||"application/octet-stream";Ie.push({type:"file",data:xe,mimeType:Fe,filename:Wh(Fe)})}}if(Ie.length>0){let Xe=c(),ot=Y,je={id:`agent-media-${typeof ot=="string"&&ot.length>0?`${ot}-${Xe}`:String(Xe)}`,role:"assistant",content:"",contentParts:Ie,createdAt:new Date().toISOString(),streaming:!1,sequence:Xe,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:fe}};f(je);let xe=y;xe&&(xe.streaming=!1,f(xe)),y=null,E.current=null}}else if(O==="execution_complete"){let R=v.kind??ae;R==="agent"&&ue&&(ue.status=v.success?"complete":"error",ue.completedAt=Be(v.completedAt),ue.stopReason=v.stopReason);let T=y;T&&(R==="flow"&&T.streaming!==!1?St(T):(T.streaming=!1,f(T)),y=null),W=null,M="",vt=null,n({type:"status",status:"idle",terminal:!0})}else if(O==="execution_error"){let R=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(R)})}else if(O!=="ping"){if(O==="approval_start"){let R=v.approvalId??`approval-${c()}`,T={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.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(T)}else if(O==="step_await"&&v.awaitReason==="approval_required"){let R=v.approvalId??`approval-${c()}`,T={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.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(T)}else if(O==="approval_complete"){let R=v.approvalId;if(R){let I={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:R,status:v.decision??"approved",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(I)}}else if(O==="artifact_start"||O==="artifact_delta"||O==="artifact_update"||O==="artifact_complete"){if(O==="artifact_start"){let R=v.artifactType,T=String(v.id),I=typeof v.title=="string"?v.title:void 0,K=v.file,B;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(B={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:T,artifactType:R,title:I,component:typeof v.component=="string"?v.component:void 0,...B?{file:B}:{}});let j=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(he.set(T,{markdown:"",title:I,file:B,...j?{props:j}:{}}),!ve.has(T)){ve.add(T);let Y=Un(this.config.features?.artifacts,{artifactType:R,...B?{file:B}:{}}),Ke=typeof v.component=="string"?v.component:void 0,Ie={id:`artifact-ref-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:us(Y,{artifactId:T,title:I,artifactType:R,status:"streaming",...B?{file:B}:{},...Ke?{component:Ke}:{}})};pe.set(T,Ie),f(Ie)}}else if(O==="artifact_delta"){let R=String(v.id),T=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:R,artDelta:T});let I=he.get(R);I&&(I.markdown+=T)}else if(O==="artifact_update"){let R=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:R,component:typeof v.component=="string"?v.component:void 0});let T=he.get(String(v.id));T&&(T.props={...T.props??{},...R})}else if(O==="artifact_complete"){let R=String(v.id);n({type:"artifact_complete",id:R});let T=pe.get(R);if(T){T.streaming=!1;try{let I=JSON.parse(T.rawContent??"{}");if(I.props){I.props.status="complete";let K=he.get(R);K?.markdown&&(I.props.markdown=K.markdown),K?.file&&(I.props.file=K.file),I.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(I.props.componentProps=K.props)}T.rawContent=JSON.stringify(I)}catch{}he.delete(R),f(T),pe.delete(R)}}}else if(O==="transcript_insert"){let R=v.message;if(!R||typeof R!="object")continue;let T=String(R.id??`msg-${c()}`),I=R.role,B={id:T,role:I==="user"?"user":I==="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(B),B.rawContent)try{let Y=JSON.parse(B.rawContent)?.props?.artifactId;typeof Y=="string"&&ve.add(Y)}catch{}y=null,E.current=null,ze.delete(T),Te.delete(T)}else if(O==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let R=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(R)});let T=y;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}else if(O==="step_error"||O==="dispatch_error"||O==="flow_error"){let R=null;if(v.error instanceof Error)R=v.error;else if(O==="dispatch_error"){let T=v.message??v.error;T!=null&&T!==""&&(R=new Error(String(T)))}else{let T=v.error;typeof T=="string"&&T!==""?R=new Error(T):T!=null&&typeof T=="object"&&Reflect.has(T,"message")&&(R=new Error(String(T.message??T)))}if(R){n({type:"error",error:R});let T=y;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:S,value:O}=await s.read();if(S)break;i+=a.decode(O,{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()=>{}}},Ks=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},yc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},bc=()=>{let e=hb();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)}},vc=()=>{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=ig(n,lg|cg);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:()=>{}}},yb=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=ig(s,lg|cg),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},xc=()=>{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 ug="4.16.0";var To=ug;var vb="https://api.runtype.com/v1/dispatch",li="https://api.runtype.com";function xb(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 Cb(e){switch(e){case"json":return vc;case"regex-json":return bc;case"xml":return xc;default:return yc}}var gg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function wb(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=gg(n);if(!gg(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ks(e);return Ks(t)!==null&&a===null?t:e}var zr=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??vb,this.headers={"Content-Type":"application/json","X-Persona-Version":To,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Cb(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 Ns(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=ju(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$/,"")||li}/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":To},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$/,"")||li}/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":To},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Cc).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(i.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/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?Fu(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,g;for(let b=0;;b++){if(g=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||li}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:g}=await this.sendWithClientToolsDiff(a,d,b=>{let f={...p,...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&&g(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Cc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...zs(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,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let g={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=g,r(g),g},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,g=E=>{let I=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,h=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,W=E.tools?E.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...E,reasoning:I,toolCall:h,tools:W}},b=E=>{if(E.role!=="assistant"||E.variant)return!0;let I=Array.isArray(E.contentParts)&&E.contentParts.length>0,h=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||I||h||!!E.stopReason},f=E=>{b(E)&&n({type:"message",message:g(E)})},x=null,C=null,S={current:null},M={current:null},P=null,T="",L=new Map,H=new Map,O=new Map,_=new Map,U=new Map,z={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},A=E=>{if(E==null)return null;try{return String(E)}catch{return null}},G=E=>A(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),Q=E=>A(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),le=o,J=!1,me=()=>{if(x)return x;let E,I="",h=P;return!J&&le?(E=le,J=!0,I=r??""):le&&h?E=`${le}_${h}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:E,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(x),x},ee=(E,I)=>{z.lastId=I,E&&z.byStep.set(E,I)},ye=(E,I)=>{let h=E.reasoningId??E.id,W=G(E);if(h){let B=String(h);return ee(W,B),B}if(W){let B=z.byStep.get(W);if(B)return z.lastId=B,B}if(z.lastId&&!I)return z.lastId;if(!I)return null;let R=`reason-${c()}`;return ee(W,R),R},Z=E=>{let I=_.get(E);if(I)return I;let h={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return _.set(E,h),f(h),h},ue=(E,I)=>{Y.lastId=I,E&&Y.byCall.set(E,I)},te=new Set,fe=new Map,be=new Set,he=new Map,Be=E=>{if(!E)return!1;let I=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},rt=(E,I)=>{let h=E.toolId??E.id,W=Q(E);if(h){let B=String(h);return ue(W,B),B}if(W){let B=Y.byCall.get(W);if(B)return Y.lastId=B,B}if(Y.lastId&&!I)return Y.lastId;if(!I)return null;let R=`tool-${c()}`;return ue(W,R),R},$e=E=>{let I=U.get(E);if(I)return I;let h={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return U.set(E,h),f(h),h},Ve=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let I=Number(E);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(E);if(!Number.isNaN(h))return h}return Date.now()},Le=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},_e=new Map,we=new Map,ae=new Map,Re=(E,I,h)=>{let W=ae.get(E);W||(W=[],ae.set(E,W));let R=0,B=W.length;for(;R<B;){let $=R+B>>>1;W[$].seq<I?R=$+1:B=$}W[R]?.seq===I?W[R]={seq:I,text:h}:W.splice(R,0,{seq:I,text:h});let V="";for(let $=0;$<W.length;$++)V+=W[$].text;return V},ct=(E,I)=>{let h=Le(I),W=we.get(E.id),R=wb(W,h);E.rawContent=R;let B=_e.get(E.id),V=pe=>{let Pe=E.content??"";pe.trim()!==""&&(Pe.trim().length===0||pe.startsWith(Pe)||pe.trimStart().startsWith(Pe.trim()))&&(E.content=pe)},$=()=>{if(B){let pe=B.close?.();pe instanceof Promise&&pe.catch(()=>{})}_e.delete(E.id),we.delete(E.id),E.streaming=!1,f(E)};if(!B){V(h),$();return}let K=Ks(R);if(K!==null&&K.trim()!==""){V(K),$();return}let de=pe=>{let Pe=typeof pe=="string"?pe:pe?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let ze=B.getExtractedText();return ze!==null&&ze.trim()!==""?ze:h},Ue;try{Ue=B.processChunk(R)}catch{V(h),$();return}if(Ue instanceof Promise){Ue.then(pe=>{V(de(pe)),$()}).catch(()=>{V(h),$()});return}V(de(Ue)),$()},et=null,vt=(E,I,h,W)=>{E.rawContent=I,_e.has(E.id)||_e.set(E.id,this.createStreamParser());let R=_e.get(E.id),B=I.trim().startsWith("{")||I.trim().startsWith("[");if(B&&we.set(E.id,I),R.__isPlainTextParser===!0){E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E);return}let $=R.processChunk(I);if($ instanceof Promise)$.then(K=>{let de=typeof K=="string"?K:K?.text??null;de!==null&&de.trim()!==""?(E.content=de,f(E)):!B&&!I.trim().startsWith("<")&&(E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(E.content=K,f(E)):!B&&!I.trim().startsWith("<")&&(E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E))}},wn=(E,I)=>{let h=I??E.content;if(h==null||h===""){E.streaming=!1,f(E);return}let R=we.get(E.id)??Le(h);E.rawContent=R;let B=_e.get(E.id),V=null,$=!1;if(B&&(V=B.getExtractedText(),V===null&&(V=Ks(R)),V===null)){let K=B.processChunk(R);K instanceof Promise?($=!0,K.then(de=>{let Ue=typeof de=="string"?de:de?.text??null;Ue!==null&&(E.content=Ue,E.streaming=!1,_e.delete(E.id),we.delete(E.id),f(E))}).catch(()=>{})):V=typeof K=="string"?K:K?.text??null}if(!$){V!==null&&V.trim()!==""?E.content=V:we.has(E.id)||(E.content=Le(h));let K=_e.get(E.id);if(K){let de=K.close?.();de instanceof Promise&&de.catch(()=>{}),_e.delete(E.id)}we.delete(E.id),E.streaming=!1,f(E)}},An=(E,I,h)=>{let W=H.get(E);if(W)return W;let R={id:`nested-${I}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(E,R),f(R),R},Ze=[],ke,ve=new Map,tt=0,Te="agent",Ce=!1,re=null,Ae=null,Sn=new Map,ne=this.config.iterationDisplay??"separate";for(ke=()=>{for(let E=0;E<Ze.length;E++){let I=Ze[E].payloadType,h=Ze[E].payload;if(!Ce&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&R){L.set(W,R),An(W,R,"reasoning");continue}let B=ye(h,!0)??`reason-${c()}`,V=Z(B);V.reasoning=V.reasoning??{id:B,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??Ve(h.startedAt??h.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(V.reasoning.scope=h.scope),V.streaming=!0,V.reasoning.status="streaming",f(V)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),f($));continue}let R=ye(h,!1)??ye(h,!0)??`reason-${c()}`,B=Z(R);B.reasoning=B.reasoning??{id:R,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Ve(h.startedAt??h.timestamp);let V=h.reasoningText??h.text??h.delta??"";if(V&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=Re(R,$,String(V));B.reasoning.chunks=[K]}else B.reasoning.chunks.push(String(V))}if(B.reasoning.status=h.done?"complete":"streaming",h.done){B.reasoning.completedAt=Ve(h.completedAt??h.timestamp);let $=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-$)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let de=typeof h.text=="string"?h.text:"";de&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(de),K.reasoning.status="complete",K.streaming=!1,f(K)}L.delete(W),H.delete(W);continue}let R=ye(h,!1)??ye(h,!0)??`reason-${c()}`,B=typeof h.text=="string"?h.text:"";!_.get(R)&&(B||h.scope==="loop")&&Z(R);let V=_.get(R);if(V?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(V.reasoning.scope=h.scope),B&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(B),V.reasoning.status="complete",V.reasoning.completedAt=Ve(h.completedAt??h.timestamp);let K=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-K),V.streaming=!1,f(V)}let $=G(h);$&&z.byStep.delete($)}else if(I==="tool_start"){x&&(x.streaming=!1,f(x),x=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??rt(h,!0)??`tool-${c()}`,R=h.toolName??h.name;if(Be(R)){te.add(W);continue}ue(Q(h),W);let B=$e(W),V=B.toolCall??{id:W,status:"pending"};V.name=R??V.name,V.status="running",h.parameters!==void 0?V.args=h.parameters:h.args!==void 0&&(V.args=h.args),V.startedAt=V.startedAt??Ve(h.startedAt??h.timestamp),V.completedAt=void 0,V.durationMs=void 0,B.toolCall=V,B.streaming=!0,h.executionId&&(B.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(B)}else if(I==="tool_output_delta"){let W=rt(h,!1)??rt(h,!0)??`tool-${c()}`;if(te.has(W))continue;let R=$e(W),B=R.toolCall??{id:W,status:"running"};B.startedAt=B.startedAt??Ve(h.startedAt??h.timestamp);let V=h.text??h.delta??h.message??"";V&&(B.chunks=B.chunks??[],B.chunks.push(String(V))),B.status="running",R.toolCall=B,R.streaming=!0;let $=h.agentContext;($||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),f(R)}else if(I==="tool_complete"){let W=rt(h,!1)??rt(h,!0)??`tool-${c()}`;if(te.has(W)){te.delete(W);continue}let R=$e(W),B=R.toolCall??{id:W,status:"running"};B.status="complete",h.result!==void 0&&(B.result=h.result),typeof h.duration=="number"&&(B.duration=h.duration),B.completedAt=Ve(h.completedAt??h.timestamp);let V=h.duration??h.executionTime;if(typeof V=="number")B.durationMs=V;else{let de=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-de)}R.toolCall=B,R.streaming=!1;let $=h.agentContext;($||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),f(R);let K=Q(h);K&&Y.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,R=W??h.toolId??`local-${c()}`,B=$e(R),V=h.toolName,$=h.origin==="webmcp"&&!or(V)?`webmcp:${V}`:V,K=or($),de=B.toolCall??{id:R,status:"pending"};de.name=$,de.args=h.parameters,de.status=K?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??Ve(h.startedAt??h.timestamp??h.awaitedAt),K?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,B.toolCall=de,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:h.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},f(B)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&R){L.set(W,R);continue}let B=x;B&&(Te==="flow"?(wn(B),et=B):(B.streaming=!1,f(B)),x=null),P=typeof h.id=="string"?h.id:P,T=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,R=W?L.get(W):void 0;if(W&&R){let V=typeof h.delta=="string"?h.delta:"",$=(O.get(W)??"")+V;if(O.set(W,$),$.trim()==="")continue;let K=An(W,R);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:R},vt(K,$,V,void 0);continue}if(P=typeof h.id=="string"?h.id:P,Te==="flow"){let V=typeof h.delta=="string"?h.delta:"";if(T+=V,T.trim()==="")continue;let $=me();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},vt($,T,V,void 0),C=$;continue}let B=me();B.content+=h.delta??"",B.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:Ae?.agentName},C=B,f(B)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)){let B=H.get(W);B&&wn(B),L.delete(W),O.delete(W),H.delete(W);continue}let R=x;R&&(Te==="flow"?(wn(R),et=R):((R.content??"")===""&&typeof h.text=="string"&&(R.content=h.text),R.streaming=!1,f(R)),x=null),P=null,T=""}else if(I==="step_complete"){let W=h.stepType,R=h.executionType;if(W==="tool"||R==="context")continue;if(h.success===!1){let B=h.error,V=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let $=x;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"});continue}{let B=et;et=null;let V=h.stopReason,$=h.result?.response;if(B)V&&(B.stopReason=V),$!=null?ct(B,$):B.streaming!==!1&&(_e.delete(B.id),we.delete(B.id),B.streaming=!1,f(B));else{let K=$!=null&&$!=="";if(K||V){let de=me();V&&(de.stopReason=V),K?wn(de,$):(de.streaming=!1,f(de))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",Ce=!0,Te==="agent"&&(Ae={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ve(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(Ae&&(Ae.currentIteration=W),ne==="separate"&&W>1){let R=x;R&&(R.streaming=!1,f(R),Sn.set(W-1,R),x=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??Y.lastId;if(W){let R=U.get(W);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(h.delta??""),f(R))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,R=x??C;if(W&&R!==null){let B=h.id;(!B||R.agentMetadata?.turnId===B)&&(R.stopReason=W,f(R))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ve.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ve.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),R=ve.get(W);ve.delete(W);let B=(typeof h.mediaType=="string"?h.mediaType:void 0)??R?.mediaType??"application/octet-stream",V=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(V)K={type:"media",data:V,mediaType:B};else if($){let Pe=B.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:B}}let de=h.toolCallId??R?.toolCallId,Ue=K?[K]:[],pe=[];for(let Pe of Ue){if(!Pe||typeof Pe!="object")continue;let ze=Pe,je=typeof ze.type=="string"?ze.type:void 0,He=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",Se=null,nt="";if(je==="media"){let St=typeof ze.data=="string"?ze.data:void 0;if(!St)continue;nt=He.length>0?He:"application/octet-stream",Se=`data:${nt};base64,${St}`}else if(je==="image-url"){let St=typeof ze.url=="string"?ze.url:void 0;if(!St)continue;nt=He,Se=St}else if(je==="file-url"){let St=typeof ze.url=="string"?ze.url:void 0;if(!St)continue;nt=He,Se=St}else continue;if(Se)if(je==="image-url"||nt.startsWith("image/"))pe.push({type:"image",image:Se,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))pe.push({type:"audio",audio:Se,mimeType:nt});else if(nt.startsWith("video/"))pe.push({type:"video",video:Se,mimeType:nt});else{let St=nt||"application/octet-stream";pe.push({type:"file",data:Se,mimeType:St,filename:xb(St)})}}if(pe.length>0){let Pe=c(),ze=de,He={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:pe,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};f(He);let Se=x;Se&&(Se.streaming=!1,f(Se)),x=null,S.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&Ae&&(Ae.status=h.success?"complete":"error",Ae.completedAt=Ve(h.completedAt),Ae.stopReason=h.stopReason);let R=x;R&&(W==="flow"&&R.streaming!==!1?wn(R):(R.streaming=!1,f(R)),x=null),P=null,T="",et=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let B={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(B)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,R=String(h.id),B=typeof h.title=="string"?h.title:void 0,V=h.file,$;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&($={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:R,artifactType:W,title:B,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(R,{markdown:"",title:B,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let de=to(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),Ue=typeof h.component=="string"?h.component:void 0,pe={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:_s(de,{artifactId:R,title:B,artifactType:W,status:"streaming",...$?{file:$}:{},...Ue?{component:Ue}:{}})};fe.set(R,pe),f(pe)}}else if(I==="artifact_delta"){let W=String(h.id),R=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:R});let B=he.get(W);B&&(B.markdown+=R)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let R=he.get(String(h.id));R&&(R.props={...R.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let R=fe.get(W);if(R){R.streaming=!1;try{let B=JSON.parse(R.rawContent??"{}");if(B.props){B.props.status="complete";let V=he.get(W);V?.markdown&&(B.props.markdown=V.markdown),V?.file&&(B.props.file=V.file),B.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(B.props.componentProps=V.props)}R.rawContent=JSON.stringify(B)}catch{}he.delete(W),f(R),fe.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let R=String(W.id??`msg-${c()}`),B=W.role,$={id:R,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(f($),$.rawContent)try{let de=JSON.parse($.rawContent)?.props?.artifactId;typeof de=="string"&&be.add(de)}catch{}x=null,S.current=null,_e.delete(R),we.delete(R)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let R=x;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let R=h.message??h.error;R!=null&&R!==""&&(W=new Error(String(R)))}else{let R=h.error;typeof R=="string"&&R!==""?W=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(W=new Error(String(R.message??R)))}if(W){n({type:"error",error:W});let R=x;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:E,value:I}=await s.read();if(E)break;i+=a.decode(I,{stream:!0});let h=i.split(`
|
|
12
12
|
|
|
13
|
-
`);i=
|
|
14
|
-
`),I="message",K="",B=null;for(let Ie of T)Ie.startsWith("event:")?I=Ie.replace("event:","").trim():Ie.startsWith("data:")?K+=Ie.replace("data:","").trim():Ie.startsWith("id:")&&(B=Ie.slice(3).trim());let j=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!K){j();continue}let Y;try{Y=JSON.parse(K)}catch(Ie){n({type:"error",error:Ie instanceof Error?Ie:new Error("Failed to parse chat stream payload")});continue}let Ke=I!=="message"?I:Y.type??"message";if(this.onSSEEvent?.(Ke,Y),this.parseSSEEvent){E.current=y;let Ie=await this.handleCustomSSEEvent(Y,n,E,f,c,P);if(E.current&&E.current!==y&&(y=E.current),Ie){j();continue}}de.push({payloadType:Ke,payload:Y}),Ze(),j()}}Ze()}};function Dh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function xs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Uo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Fa="[Image]";function Oh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Nh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Fh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function zo(e){return{type:"text",text:e}}function _h(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function $h(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 jh(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 Xp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Uh=["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"],qn=[...Xp,...Uh];function zh(e){return Xp.includes(e)||e.startsWith("image/")}function _a(e){return zh(e.type)}async function Yp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;_a(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 Qp(e,t=qn,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 qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Zp(e,t){let n=qh(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"}Hl();var eu=16e3,Vh=24e3,Kh=4096,Gh=1380533830;function Jh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Gh?new Uint8Array(e,44):new Uint8Array(e)}function Xh(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 Cs=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:eu,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:eu});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new xr(Vh);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=`${Xh(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(Kh,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=Jh(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 qo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cs(e.runtype);case"browser":if(!qo.isSupported())throw new Error("Browser speech recognition not supported");return new qo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bl(e){if(e?.type==="custom"&&e.custom)return Vo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Vo({type:"runtype",runtype:e.runtype});if(qo.isSupported())return Vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function $a(e){try{return Bl(e),!0}catch{return!1}}function ws(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 Ko=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):ws(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 Cr=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 Dl(e){if(!e)return"";let t=Yh(e);return tu(t!==null?t:e)}function Yh(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 tu(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=h.pop()??"";for(let W of h){let R=W.split(`
|
|
14
|
+
`),B="message",V="",$=null;for(let pe of R)pe.startsWith("event:")?B=pe.replace("event:","").trim():pe.startsWith("data:")?V+=pe.replace("data:","").trim():pe.startsWith("id:")&&($=pe.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!V){K();continue}let de;try{de=JSON.parse(V)}catch(pe){n({type:"error",error:pe instanceof Error?pe:new Error("Failed to parse chat stream payload")});continue}let Ue=B!=="message"?B:de.type??"message";if(this.onSSEEvent?.(Ue,de),this.parseSSEEvent){S.current=x;let pe=await this.handleCustomSSEEvent(de,n,S,f,c,M);if(S.current&&S.current!==x&&(x=S.current),pe){K();continue}}Ze.push({payloadType:Ue,payload:de}),ke(),K()}}ke()}};function Ab(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Gs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ir(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ci="[Image]";function Sb(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Tb(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function wc(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Eb(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function lr(e){return{type:"text",text:e}}function Mb(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function kb(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 Lb(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 fg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Pb=["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"],no=[...fg,...Pb];function Rb(e){return fg.includes(e)||e.startsWith("image/")}function di(e){return Rb(e.type)}async function mg(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 hg(e,t=no,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 Ib(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function yg(e,t){let n=Ib(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"}Ac();var bg=16e3,Wb=24e3,Hb=4096,Bb=1380533830;function Db(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Bb?new Uint8Array(e,44):new Uint8Array(e)}function Ob(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 Js=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:bg,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:bg});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new qr(Wb);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(g=>g.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Ob(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=g=>this.handleMessage(g,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let b=g.code?` (code ${g.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(Hb,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let g=Math.max(-1,Math.min(1,p[c]));d[c]=g<0?g*32768:g*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Db(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 cr=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 dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Js(e.runtype);case"browser":if(!cr.isSupported())throw new Error("Browser speech recognition not supported");return new cr(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 Sc(e){if(e?.type==="custom"&&e.custom)return dr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return dr({type:"runtype",runtype:e.runtype});if(cr.isSupported())return dr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function pi(e){try{return Sc(e),!0}catch{return!1}}function Ys(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 pr=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):Ys(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 Vr=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 Tc(e){if(!e)return"";let t=Nb(e);return vg(t!==null?t:e)}function Nb(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 vg(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 Sg=null;var Ec=()=>Sg?Sg():Promise.resolve().then(()=>(Ag(),wg));var Ub=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function zb(e,t){return Ub.some(n=>e[n]!==t[n])}function Mc(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 As=e=>({isError:!0,content:[{type:"text",text:e}]}),cu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,du=e=>Fo(e)||e===kn,Ss=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 Cr(()=>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&&(Fo(n.name)||n.name===kn&&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 vr(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||Ol().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 $a(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=Ko.isSupported()?new Ko({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 Ol().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=Vo(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let 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(!oy(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 vr(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"?xs():n==="assistant"?Uo():`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"?xs():r==="assistant"?Uo():`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 Xs=e=>({isError:!0,content:[{type:"text",text:e}]}),Mg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,kg=e=>or(e)||e===On,Qs=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 Vr(()=>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&&(or(n.name)||n.name===On&&Ao(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 zr(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||Ec().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 pi(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=pr.isSupported()?new pr({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 Ec().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=dr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!zb(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 zr(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:p,streaming:d=!1,voiceProcessing:c,rawContent:g}=t,f={id:a??(n==="user"?Gs():n==="assistant"?ir():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...g!==void 0&&{rawContent:g}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:g=!1,voiceProcessing:b,rawContent:f}=o,C={id:p??(r==="user"?Gs():r==="assistant"?ir():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:g,...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:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
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(zo(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(zo(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=xs(),s=Uo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Wl(n.contentParts)?Fa:"",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=Nl(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=Uo();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=Nl(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!==kn?!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===kn)return{dedupeKey:u,resumeKey:f,output:Tl(),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),E;if(!C)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await C}catch(P){let W=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));return W||this.callbacks.onError?.(P instanceof Error?P:new Error(String(P))),this.markWebMcpToolComplete(d,As(W?"Aborted by cancel()":cu(P)),b),this.webMcpInflightKeys.delete(u),null}return y.signal.aborted?(this.markWebMcpToolComplete(d,As("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,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===kn?{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,As("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===kn,c=t.toolCall?.args,u=p?null:this.client.executeWebMcpToolCall(o,c,d),b="execute",f=a;try{let y;if(p?y=Tl():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,As("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,As(C||d.aborted?"Aborted by cancel()":cu(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=Un(this.config.features?.artifacts,t),r=us(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=Un(this.config.features?.artifacts,n),s=us(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(()=>(lu(),iu)).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=>Nl(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=Uo(),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=Dl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ws(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Dl(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&&du(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&&du(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)})}};import{Activity as ry,ArrowDown as sy,ArrowUp as ay,ArrowUpRight as iy,Bot as ly,ChevronDown as cy,ChevronUp as dy,ChevronRight as py,ChevronLeft as uy,Check as fy,Clipboard as gy,ClipboardCopy as my,CodeXml as hy,Copy as yy,File as by,FileCode as vy,FileSpreadsheet as xy,FileText as Cy,ImagePlus as wy,Loader as Ay,LoaderCircle as Sy,Mic as Ty,Paperclip as My,RefreshCw as Ey,Search as ky,Send as Py,ShieldAlert as Ly,ShieldCheck as Ry,ShieldX as Iy,Square as Wy,ThumbsDown as Hy,ThumbsUp as By,Upload as Dy,Volume2 as Oy,X as Ny,User as Fy,Mail as _y,Phone as $y,Calendar as jy,Clock as Uy,Building as zy,MapPin as qy,Lock as Vy,Key as Ky,CreditCard as Gy,AtSign as Jy,Hash as Xy,Globe as Yy,Link as Qy,CircleCheck as Zy,CircleX as eb,TriangleAlert as tb,Info as nb,Ban as ob,Shield as rb,ArrowLeft as sb,ArrowRight as ab,ExternalLink as ib,Ellipsis as lb,EllipsisVertical as cb,Menu as db,House as pb,Plus as ub,Minus as fb,Pencil as gb,Trash as mb,Trash2 as hb,Save as yb,Download as bb,Share as vb,Funnel as xb,Settings as Cb,RotateCw as wb,Maximize as Ab,Minimize as Sb,ShoppingCart as Tb,ShoppingBag as Mb,Package as Eb,Truck as kb,Tag as Pb,Gift as Lb,Receipt as Rb,Wallet as Ib,Store as Wb,DollarSign as Hb,Percent as Bb,Play as Db,Pause as Ob,VolumeX as Nb,Camera as Fb,Image as _b,Film as $b,Headphones as jb,MessageCircle as Ub,MessageSquare as zb,Bell as qb,Heart as Vb,Star as Kb,Eye as Gb,EyeOff as Jb,Bookmark as Xb,CalendarDays as Yb,History as Qb,Timer as Zb,Folder as ev,FolderOpen as tv,Files as nv,Sparkles as ov,Zap as rv,Sun as sv,Moon as av,Flag as iv,Monitor as lv,Smartphone as cv}from"lucide";var dv={activity:ry,"arrow-down":sy,"arrow-up":ay,"arrow-up-right":iy,bot:ly,"chevron-down":cy,"chevron-up":dy,"chevron-right":py,"chevron-left":uy,check:fy,clipboard:gy,"clipboard-copy":my,"code-xml":hy,copy:yy,file:by,"file-code":vy,"file-spreadsheet":xy,"file-text":Cy,"image-plus":wy,loader:Ay,"loader-circle":Sy,mic:Ty,paperclip:My,"refresh-cw":Ey,search:ky,send:Py,"shield-alert":Ly,"shield-check":Ry,"shield-x":Iy,square:Wy,"thumbs-down":Hy,"thumbs-up":By,upload:Dy,"volume-2":Oy,x:Ny,user:Fy,mail:_y,phone:$y,calendar:jy,clock:Uy,building:zy,"map-pin":qy,lock:Vy,key:Ky,"credit-card":Gy,"at-sign":Jy,hash:Xy,globe:Yy,link:Qy,"circle-check":Zy,"circle-x":eb,"triangle-alert":tb,info:nb,ban:ob,shield:rb,"arrow-left":sb,"arrow-right":ab,"external-link":ib,ellipsis:lb,"ellipsis-vertical":cb,menu:db,house:pb,plus:ub,minus:fb,pencil:gb,trash:mb,"trash-2":hb,save:yb,download:bb,share:vb,funnel:xb,settings:Cb,"rotate-cw":wb,maximize:Ab,minimize:Sb,"shopping-cart":Tb,"shopping-bag":Mb,package:Eb,truck:kb,tag:Pb,gift:Lb,receipt:Rb,wallet:Ib,store:Wb,"dollar-sign":Hb,percent:Bb,play:Db,pause:Ob,"volume-x":Nb,camera:Fb,image:_b,film:$b,headphones:jb,"message-circle":Ub,"message-square":zb,bell:qb,heart:Vb,star:Kb,eye:Gb,"eye-off":Jb,bookmark:Xb,"calendar-days":Yb,history:Qb,timer:Zb,folder:ev,"folder-open":tv,files:nv,sparkles:ov,zap:rv,sun:sv,moon:av,flag:iv,monitor:lv,smartphone:cv},oe=(e,t=24,n="currentColor",o=2)=>{let r=dv[e];return r?pv(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 pv(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 za={allowedTypes:qn,maxFileSize:10*1024*1024,maxFiles:4};function uv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function fv(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 wr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??za.allowedTypes,maxFileSize:t.maxFileSize??za.maxFileSize,maxFiles:t.maxFiles??za.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:za.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=Qp(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 Yp(n),s=_a(n)?URL.createObjectURL(n):null,a={id:uv(),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=_a(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=fv(t.file.type),d=oe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let p=m("span");p.textContent=Zp(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=oe("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 pu=/\s/;function gv(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(
|
|
26
|
-
`)[0]).startsWith(k.trigger):!1),s=(M,k)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${M}`,{detail:k}))}catch{}},a=Ne("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 M=jl().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===M&&(d=null),null));return d=M,M},C=()=>{yu().then(M=>{let k=M.mountInlineComposer({textarea:e.textarea,renderToken:z=>Ts(z,{render:t.renderMentionToken}),onMentionRemoved:z=>i?.untrackMention(z)});c=k.input,u=k.destroy;let F=p;F.replaceWith(k.element),p=k.element,f={next:k.element,prev:F},b?.(k.element,F),i?i.rebindComposer(k.input):d&&d.then(z=>z?.rebindComposer(k.input))}).catch(M=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",M)})};t.display==="inline"&&C();let E=[],P=new Map;for(let M of n){if(!M.showButton)continue;let k=hu({config:{...t,buttonIconName:M.buttonIconName,buttonTooltipText:M.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{y().then(F=>F?.openMenu(M.trigger))}});E.push(k),P.set(M.trigger,k.button)}let W=(M,k,F)=>{let z=P.get(k);z&&(z.setAttribute("aria-expanded",M?"true":"false"),M?z.setAttribute("aria-controls",F):z.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(M=>M.wrapper),contextRow:a,handleInput:M=>{if(i){i.handleInput();return}if(!fu(M))return;let k=p,F=k.selectionStart??0;uu(k.value,F,n)&&y().then(z=>z?.handleInput())},handleKeydown:M=>{if(i?.isMenuOpen())return i.handleKeydown(M);if(M.key==="Backspace"&&i?.hasMentions()&&!f){let k=p,F=k.selectionStart===0&&k.selectionEnd===0;if((k.value.length===0||F)&&i.removeLastChip())return M.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async M=>r(M)?(i??await y())?.dispatchInlineCommand(M)??null:null,clear:()=>i?.clear(),prefetch:()=>{jl().catch(()=>{})},onComposerSwap:M=>{b=M,f&&M(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let M of E)M.wrapper.remove();a.remove()}}}var vu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ms(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];vu(s)&&vu(r)?n[o]=Ms(s,r):n[o]=r}return n}var mn="min(440px, calc(100vw - 24px))",Ul="440px",Cv={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:mn,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)"},lt={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:Cv,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 xu(e,t){if(!(!e&&!t))return e?t?Ms(e,t):e:t}function Es(e){return e?{...lt,...e,theme:xu(lt.theme,e.theme),darkTheme:xu(lt.darkTheme,e.darkTheme),launcher:{...lt.launcher,...e.launcher,dock:{...lt.launcher?.dock,...e.launcher?.dock},clearChat:{...lt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...lt.copy,...e.copy},sendButton:{...lt.sendButton,...e.sendButton},statusIndicator:{...lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=lt.features?.artifacts,n=e.features?.artifacts,o=lt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=lt.features?.scrollBehavior,a=e.features?.scrollBehavior,i=lt.features?.streamAnimation,d=e.features?.streamAnimation,p=lt.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{...lt.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??lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...lt.layout,...e.layout,header:{...lt.layout?.header,...e.layout?.header},messages:{...lt.layout?.messages,...e.layout?.messages,avatar:{...lt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...lt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...lt.layout?.slots,...e.layout?.slots}},markdown:{...lt.markdown,...e.markdown,options:{...lt.markdown?.options,...e.markdown?.options}},messageActions:{...lt.messageActions,...e.messageActions}}:lt}var Va="16px",Ka="transparent",Cu={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"}},wu={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"}},Au={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:mn,maxWidth:Ul,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Va,canvasBackground:Ka},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 Gt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gt(e,o):o}function zl(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=Gt(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 Su(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 Tu(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]=Tu(s,r):n[o]=r}return n}function wv(e,t){return t?Tu(e,t):e}function Ga(e,t={}){let n={palette:Cu,semantic:wu,components:Au},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:wv(n.components,e?.components)};if(t.validate!==!1){let r=Su(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 ql(e){let t=zl(e),n={};for(let[w,U]of Object.entries(t)){let q=w.replace(/\./g,"-");n[`--persona-${q}`]=U.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"]??Va,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ka,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"]=Gt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let U=Gt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Gt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let 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"]=Gt(e,y.background)??y.background));let C=n["--persona-surface"],E=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",M=n["--persona-palette-colors-gray-300"]??"#d1d5db",k=!E||E===C,F=k?P:E,z=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"]??z,k&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??M),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 Av={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 Sv={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"}}},Mu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ja=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Tv=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ja()},Vl=e=>Tv(e),Mv=e=>Ga(e),Ev=e=>Ga({...e,palette:{...e?.palette,colors:{...Sv.colors,...e?.palette?.colors}}},{validate:!1}),Go=e=>{let t=Vl(e),n=Mu(e?.theme),o=Mu(e?.darkTheme);return t==="dark"?Ev(Ms(n??{},o??{})):Mv(n)},kv=e=>ql(e),Ar=(e,t)=>{let n=Go(t),o=kv(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Vl(t))},ks=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ja())});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(Ja());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 Pn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Eu(e){let t=Pn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Xa(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
22
|
+
`),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(i){let d=[];s&&d.push(lr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(lr(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Gs(),s=ir();this.activeAssistantMessageId=null;let a=n?.contentParts&&wc(n.contentParts)?ci:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(g=>g.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let b=Mc(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,g||(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=ir();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=Mc(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let g=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}`)}g=c.body}else c instanceof ReadableStream&&(g=c);g?await this.connectStream(g,{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 g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||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,g=Array.isArray(c?.questions)?c.questions:[];if(g.length===1){let b=typeof g[0]?.question=="string"?g[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,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([g,b])=>`${g}: ${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??{};d.forEach((g,b)=>{let f=typeof g?.question=="string"?g.question:"";if(!f)return;let x=c[f],C=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";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 g=await c.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||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!==On?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let g=`${t}:${c}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(g),o.push(g);let b=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===On)return{dedupeKey:g,resumeKey:f,output:fc(),toolMessage:p,startedAt:b,completedAt:Date.now()};let x=new AbortController;this.webMcpResolveControllers.add(x),r.push(x);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,x.signal),S;if(!C)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await C}catch(M){let P=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));return P||this.callbacks.onError?.(M instanceof Error?M:new Error(String(M))),this.markWebMcpToolComplete(p,Xs(P?"Aborted by cancel()":Mg(M)),b),this.webMcpInflightKeys.delete(g),null}return x.signal.aborted?(this.markWebMcpToolComplete(p,Xs("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:f,output:S,toolMessage:p,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===On?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,Xs("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let x=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x))return;this.webMcpInflightKeys.add(x);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(x)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(x)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===On,c=t.toolCall?.args,g=d?null:this.client.executeWebMcpToolCall(o,c,p),b="execute",f=a;try{let x;if(d?x=fc():g?x=await g:x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Xs("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,x,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,x,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,Xs(C||p.aborted?"Aborted by cancel()":Mg(x)),a),C||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}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=to(this.config.features?.artifacts,t),r=_s(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=to(this.config.features?.artifacts,n),s=_s(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(()=>(Eg(),Tg)).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=>Mc(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=ir(),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=Tc(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ys(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Tc(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,g=n.approval;a.approval={...c,...g,executionId:g.executionId||c.executionId,toolName:g.toolName||c.toolName,description:g.description||c.description,toolType:g.toolType??c.toolType,reason:g.reason??c.reason,parameters:g.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&kg(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,g=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,x=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&kg(f)&&r.toolCall?.status==="complete";(g||b||x)&&(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)})}};import{Activity as qb,ArrowDown as Vb,ArrowUp as Kb,ArrowUpRight as Gb,Bot as Jb,ChevronDown as Yb,ChevronUp as Xb,ChevronRight as Qb,ChevronLeft as Zb,Check as ev,Clipboard as tv,ClipboardCopy as nv,CodeXml as ov,Copy as rv,File as sv,FileCode as av,FileSpreadsheet as iv,FileText as lv,ImagePlus as cv,Loader as dv,LoaderCircle as pv,Mic as uv,Paperclip as gv,RefreshCw as fv,Search as mv,Send as hv,ShieldAlert as yv,ShieldCheck as bv,ShieldX as vv,Square as xv,ThumbsDown as Cv,ThumbsUp as wv,Upload as Av,Volume2 as Sv,X as Tv,User as Ev,Mail as Mv,Phone as kv,Calendar as Lv,Clock as Pv,Building as Rv,MapPin as Iv,Lock as Wv,Key as Hv,CreditCard as Bv,AtSign as Dv,Hash as Ov,Globe as Nv,Link as Fv,CircleCheck as _v,CircleX as $v,TriangleAlert as jv,Info as Uv,Ban as zv,Shield as qv,ArrowLeft as Vv,ArrowRight as Kv,ExternalLink as Gv,Ellipsis as Jv,EllipsisVertical as Yv,Menu as Xv,House as Qv,Plus as Zv,Minus as ex,Pencil as tx,PenLine as nx,Trash as ox,Trash2 as rx,Save as sx,Download as ax,Share as ix,Funnel as lx,Settings as cx,RotateCw as dx,Maximize as px,Minimize as ux,ShoppingCart as gx,ShoppingBag as fx,Package as mx,Truck as hx,Tag as yx,Gift as bx,Receipt as vx,Wallet as xx,Store as Cx,DollarSign as wx,Percent as Ax,Play as Sx,Pause as Tx,VolumeX as Ex,Camera as Mx,Image as kx,Film as Lx,Headphones as Px,MessageCircle as Rx,MessageSquare as Ix,Bell as Wx,Heart as Hx,Star as Bx,Eye as Dx,EyeOff as Ox,Bookmark as Nx,CalendarDays as Fx,History as _x,Timer as $x,Folder as jx,FolderOpen as Ux,Files as zx,ChartColumn as qx,Sparkles as Vx,Zap as Kx,Sun as Gx,Moon as Jx,Flag as Yx,Lightbulb as Xx,Monitor as Qx,Smartphone as Zx}from"lucide";var eC={activity:qb,"arrow-down":Vb,"arrow-up":Kb,"arrow-up-right":Gb,bot:Jb,"chevron-down":Yb,"chevron-up":Xb,"chevron-right":Qb,"chevron-left":Zb,check:ev,clipboard:tv,"clipboard-copy":nv,"code-xml":ov,copy:rv,file:sv,"file-code":av,"file-spreadsheet":iv,"file-text":lv,"image-plus":cv,loader:dv,"loader-circle":pv,mic:uv,paperclip:gv,"refresh-cw":fv,search:mv,send:hv,"shield-alert":yv,"shield-check":bv,"shield-x":vv,square:xv,"thumbs-down":Cv,"thumbs-up":wv,upload:Av,"volume-2":Sv,x:Tv,user:Ev,mail:Mv,phone:kv,calendar:Lv,clock:Pv,building:Rv,"map-pin":Iv,lock:Wv,key:Hv,"credit-card":Bv,"at-sign":Dv,hash:Ov,globe:Nv,link:Fv,"circle-check":_v,"circle-x":$v,"triangle-alert":jv,info:Uv,ban:zv,shield:qv,"arrow-left":Vv,"arrow-right":Kv,"external-link":Gv,ellipsis:Jv,"ellipsis-vertical":Yv,menu:Xv,house:Qv,plus:Zv,minus:ex,pencil:tx,"pen-line":nx,trash:ox,"trash-2":rx,save:sx,download:ax,share:ix,funnel:lx,settings:cx,"rotate-cw":dx,maximize:px,minimize:ux,"shopping-cart":gx,"shopping-bag":fx,package:mx,truck:hx,tag:yx,gift:bx,receipt:vx,wallet:xx,store:Cx,"dollar-sign":wx,percent:Ax,play:Sx,pause:Tx,"volume-x":Ex,camera:Mx,image:kx,film:Lx,headphones:Px,"message-circle":Rx,"message-square":Ix,bell:Wx,heart:Hx,star:Bx,eye:Dx,"eye-off":Ox,bookmark:Nx,"calendar-days":Fx,history:_x,timer:$x,folder:jx,"folder-open":Ux,files:zx,"chart-column":qx,sparkles:Vx,zap:Kx,sun:Gx,moon:Jx,flag:Yx,lightbulb:Xx,monitor:Qx,smartphone:Zx},se=(e,t=24,n="currentColor",o=2)=>{let r=eC[e];return r?tC(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 tC(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var fi={allowedTypes:no,maxFileSize:10*1024*1024,maxFiles:4};function nC(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function oC(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 Kr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??fi.allowedTypes,maxFileSize:t.maxFileSize??fi.maxFileSize,maxFiles:t.maxFiles??fi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:fi.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=hg(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 mg(n),s=di(n)?URL.createObjectURL(n):null,a={id:nC(),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=y("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=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=oC(t.file.type),p=se(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=y("span");d.textContent=yg(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=y("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=se("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 Lg=/\s/;function rC(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===""||Lg.test(o)}function sC(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 rC(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
|
|
24
|
+
`||a==="\uFFFC"||!r&&Lg.test(a))return null;s--}return null}function Pg(e,t,n){for(let o of n){let r=sC(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Rg(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Ig(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"},_t=1e5,mi=_t+1;var aC=8,iC=8,kc=10,Lc=new WeakMap,Wg=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,lC=e=>{let t=e.getRootNode?.();return Wg(t)?t:e.ownerDocument.body},Pc=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function $t(e){Lc.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=aC,viewportPadding:a=iC}=e,i=()=>t.ownerDocument,p=()=>i().defaultView??window,d=null,c=null,g=null,b=!1,f=!1,x=!1,C=()=>(typeof o=="function"?o():o).trim(),S=()=>{g?.(),g=null,d?.remove(),d=null,c=null},M=()=>{if(!d)return;let Y=i(),A=p(),G=t.getBoundingClientRect(),Q=d.getBoundingClientRect(),le=Y.documentElement.clientWidth||A.innerWidth,J=Y.documentElement.clientHeight||A.innerHeight,me=le-a-Q.width,ee=G.left+G.width/2-Q.width/2,ye=Pc(ee,a,me),Z=G.top-a,ue=J-a-G.bottom,te=Q.height+s,fe=Z>=te||Z>=ue?"top":"bottom",be=fe==="top"?G.top-s-Q.height:G.bottom+s,he=J-a-Q.height,Be=Pc(be,a,he),rt=G.left+G.width/2,$e=Math.max(kc,Q.width-kc),Ve=Pc(rt-ye,kc,$e);d.dataset.placement=fe,d.style.left=`${ye}px`,d.style.top=`${Be}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Ve}px`)},P=()=>{if(x||!r||d||!t.isConnected)return;let Y=C(),A=lC(t);if(!Y||!A)return;let G=i(),Q=p();d=G.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(mi),c=G.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=Y,d.appendChild(c);let le=G.createElement("span");le.className="persona-control-tooltip__arrow",d.appendChild(le),A.appendChild(d),M(),d.dataset.state="open";let J=()=>{if(!t.isConnected){S();return}c&&(c.textContent=C()),M()};Q.addEventListener("scroll",J,!0),Q.addEventListener("resize",J);let me=t.getRootNode(),ee=Wg(me)?me:G.documentElement,ye=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||S()});ye?.observe(ee,{childList:!0,subtree:!0}),g=()=>{Q.removeEventListener("scroll",J,!0),Q.removeEventListener("resize",J),ye?.disconnect()}},T=()=>{b||f?P():S()},L=()=>{let Y=p();(!Y.matchMedia||!Y.matchMedia("(hover: none)").matches)&&(b=!0,T())},H=()=>{b=!1,T()},O=()=>{f=!0,T()},_=()=>{f=!1,T()},U=Y=>{Y.key==="Escape"&&(b=!1,f=!1,S())};n.addEventListener("mouseenter",L),n.addEventListener("mouseleave",H),t.addEventListener("focus",O),t.addEventListener("blur",_),t.addEventListener("keydown",U);let z={get isOpen(){return d!==null},show:P,hide:S,reposition:M,destroy:()=>{x||(x=!0,S(),n.removeEventListener("mouseenter",L),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",O),t.removeEventListener("blur",_),t.removeEventListener("keydown",U),Lc.delete(t))}};return Lc.set(t,z),z}function Hg(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=y("div","persona-send-button-wrapper"),d=Me("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=se(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),p.appendChild(d),$t({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??i}),{button:d,wrapper:p}}var{setLoader:aM,load:cC}=Fr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Rc=cC;var{setLoader:cM,load:dC}=Fr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Bg=dC;function Zs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Me("span",{className:In("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=se(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=y("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Me("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Dg(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Ig(t).filter(T=>T.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(T=>T.sources.some(L=>typeof L.matchCommand=="function")),r=T=>o.some(L=>L.trigger?L.position==="line-start"?T.split(`
|
|
25
|
+
`).some(O=>O.startsWith(L.trigger)):(L.position==="anywhere"?T:T.split(`
|
|
26
|
+
`)[0]).startsWith(L.trigger):!1),s=(T,L)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:L}))}catch{}},a=Me("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,g=null,b=null,f=null,x=()=>{if(i)return Promise.resolve(i);if(p)return p;let T=Rc().then(L=>(i=L.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:P,emit:s}),i)).catch(L=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",L),p===T&&(p=null),null));return p=T,T},C=()=>{Bg().then(T=>{let L=T.mountInlineComposer({textarea:e.textarea,renderToken:O=>Zs(O,{render:t.renderMentionToken}),onMentionRemoved:O=>i?.untrackMention(O)});c=L.input,g=L.destroy;let H=d;H.replaceWith(L.element),d=L.element,f={next:L.element,prev:H},b?.(L.element,H),i?i.rebindComposer(L.input):p&&p.then(O=>O?.rebindComposer(L.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&C();let S=[],M=new Map;for(let T of n){if(!T.showButton)continue;let L=Hg({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{x().then(H=>H?.openMenu(T.trigger))}});S.push(L),M.set(T.trigger,L.button)}let P=(T,L,H)=>{let O=M.get(L);O&&(O.setAttribute("aria-expanded",T?"true":"false"),T?O.setAttribute("aria-controls",H):O.removeAttribute("aria-controls"))};return{affordanceButtons:S.map(T=>T.wrapper),contextRow:a,handleInput:T=>{if(i){i.handleInput();return}if(!Rg(T))return;let L=d,H=L.selectionStart??0;Pg(L.value,H,n)&&x().then(O=>O?.handleInput())},handleKeydown:T=>{if(i?.isMenuOpen())return i.handleKeydown(T);if(T.key==="Backspace"&&i?.hasMentions()&&!f){let L=d,H=L.selectionStart===0&&L.selectionEnd===0;if((L.value.length===0||H)&&i.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(i??await x())?.dispatchInlineCommand(T)??null:null,clear:()=>i?.clear(),prefetch:()=>{Rc().catch(()=>{})},onComposerSwap:T=>{b=T,f&&T(f.next,f.prev)},destroy:()=>{i?.destroy(),g?.();for(let T of S)T.wrapper.remove();a.remove()}}}var Og=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ea(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Og(s)&&Og(r)?n[o]=ea(s,r):n[o]=r}return n}var xn="min(440px, calc(100vw - 24px))",Ic="440px",pC={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:xn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},st={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:pC,copy:{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 Ng(e,t){if(!(!e&&!t))return e?t?ea(e,t):e:t}function ta(e){return e?{...st,...e,theme:Ng(st.theme,e.theme),darkTheme:Ng(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,n=e.features?.artifacts,o=st.features?.scrollToBottom,r=e.features?.scrollToBottom,s=st.features?.scrollBehavior,a=e.features?.scrollBehavior,i=st.features?.streamAnimation,p=e.features?.streamAnimation,d=st.features?.askUserQuestion,c=e.features?.askUserQuestion,g=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},x=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...st.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...g!==void 0?{artifacts:g}:{},...x!==void 0?{streamAnimation:x}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}var hi="16px",yi="transparent",Fg={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"}},_g={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"}},$g={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:xn,maxWidth:Ic,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:hi,canvasBackground:yi},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",itemGap:"8px",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",itemGap:"8px",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",itemGap:"8px",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"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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 Xt(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."))?Xt(e,o):o}function Wc(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let p=Xt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function jg(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 Ug(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]=Ug(s,r):n[o]=r}return n}function uC(e,t){return t?Ug(e,t):e}function bi(e,t={}){let n={palette:Fg,semantic:_g,components:$g},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:uC(n.components,e?.components)};if(t.validate!==!1){let r=jg(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 Hc(e){let t=Wc(e),n={};for(let[A,G]of Object.entries(t)){let Q=A.replace(/\./g,"-");n[`--persona-${Q}`]=G.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"]??hi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??yi,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-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??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";let r=n["--persona-components-introCard-background"],s=n["--persona-components-introCard-shadow"],a=(!r||r==="transparent"||r==="none")&&(!s||s==="none"),i=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=a&&i==="1.5rem"?"1.5rem 0":i,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"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-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",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 p=n["--persona-components-markdown-heading-h1-fontSize"];p&&(n["--persona-md-h1-size"]=p);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let g=n["--persona-components-markdown-heading-h2-fontWeight"];g&&(n["--persona-md-h2-weight"]=g);let b=n["--persona-components-markdown-prose-fontFamily"];b&&b!=="inherit"&&(n["--persona-md-prose-font-family"]=b),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-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",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 f=e.components,x=f?.iconButton;x&&(x.background&&(n["--persona-icon-btn-bg"]=x.background),x.border&&(n["--persona-icon-btn-border"]=x.border),x.color&&(n["--persona-icon-btn-color"]=x.color),x.padding&&(n["--persona-icon-btn-padding"]=x.padding),x.borderRadius&&(n["--persona-icon-btn-radius"]=x.borderRadius),x.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=x.hoverBackground),x.hoverColor&&(n["--persona-icon-btn-hover-color"]=x.hoverColor),x.activeBackground&&(n["--persona-icon-btn-active-bg"]=x.activeBackground),x.activeBorder&&(n["--persona-icon-btn-active-border"]=x.activeBorder));let C=f?.labelButton;C&&(C.background&&(n["--persona-label-btn-bg"]=C.background),C.border&&(n["--persona-label-btn-border"]=C.border),C.color&&(n["--persona-label-btn-color"]=C.color),C.padding&&(n["--persona-label-btn-padding"]=C.padding),C.borderRadius&&(n["--persona-label-btn-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-label-btn-hover-bg"]=C.hoverBackground),C.fontSize&&(n["--persona-label-btn-font-size"]=C.fontSize),C.gap&&(n["--persona-label-btn-gap"]=C.gap));let S=f?.toggleGroup;S&&(S.gap&&(n["--persona-toggle-group-gap"]=S.gap),S.borderRadius&&(n["--persona-toggle-group-radius"]=S.borderRadius));let M=f?.artifact;if(M?.toolbar){let A=M.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Xt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(M?.tab){let A=M.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(M?.pane){let A=M.pane;if(A.toolbarBackground){let G=Xt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(M?.card){let A=M.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(M?.inline){let A=M.inline;A.background&&(n["--persona-artifact-inline-bg"]=Xt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Xt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Xt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Xt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Xt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let P=f?.code;P&&(P.keywordColor&&(n["--persona-code-keyword-color"]=P.keywordColor),P.stringColor&&(n["--persona-code-string-color"]=P.stringColor),P.commentColor&&(n["--persona-code-comment-color"]=P.commentColor),P.numberColor&&(n["--persona-code-number-color"]=P.numberColor),P.tagColor&&(n["--persona-code-tag-color"]=P.tagColor),P.attrColor&&(n["--persona-code-attr-color"]=P.attrColor),P.propertyColor&&(n["--persona-code-property-color"]=P.propertyColor),P.lineNumberColor&&(n["--persona-code-line-number-color"]=P.lineNumberColor),P.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=P.gutterBorderColor),P.background&&(n["--persona-code-bg"]=Xt(e,P.background)??P.background));let T=n["--persona-surface"],L=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",O=n["--persona-palette-colors-gray-200"]??"#e5e7eb",_=n["--persona-palette-colors-gray-300"]??"#d1d5db",U=!L||L===T,z=U?H:L,Y=U?O:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Y,U&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??_),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var gC={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 fC={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"}}},zg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},vi=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",mC=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":vi()},Bc=e=>mC(e),hC=e=>bi(e),yC=e=>bi({...e,palette:{...e?.palette,colors:{...fC.colors,...e?.palette?.colors}}},{validate:!1}),ur=e=>{let t=Bc(e),n=zg(e?.theme),o=zg(e?.darkTheme);return t==="dark"?yC(ea(n??{},o??{})):hC(n)},bC=e=>Hc(e),Gr=(e,t)=>{let n=ur(t),o=bC(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Bc(t))},na=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(vi())});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(vi());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())}};var Eo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function Nn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function qg(e){let t=Nn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function xi(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 gr(e){let t=qg(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 Mo(e){switch(gr(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=qg(e.path);return t?t.toUpperCase():"File"}}}function Vg(e){let t=e.markdown??"";return e.file?{filename:Nn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:xi(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Dc="http://www.w3.org/2000/svg";function Kg(e){let t=document.createElementNS(Dc,"svg");t.setAttribute("class",In("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Dc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Dc,"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 ko=(e,t,n)=>{let o=n;for(let r of t){let s=y("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Gg(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)),ko(e,t,0)}var Oc="persona-artifact-status-label",Jg="persona-artifact-status-detail",Yg="data-artifact-status-label",Nc=new Map,Xg=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Jr(e){e&&Nc.delete(e)}function vC(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Mo(t):e.artifactType==="component"?"Component":"Document"}function Yr(e,t,n){let o=vC(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=Nc.get(a);e.status!=="complete"&&i===void 0&&(i=Xg(),Nc.set(a,i));let p=i===void 0?0:Math.max(0,Xg()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",g=d?0:c.length,b=d||c===""?0:c.split(`
|
|
29
|
+
`).length,f=e.artifactType==="markdown"?e.file:void 0,x={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:g,lines:b,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(x);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 xC(e){e.className=Oc,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 fr(e,t,n){let o=e.querySelector(`:scope > .${Oc}`);o||(o=y("span",Oc),e.appendChild(o)),o.getAttribute(Yg)!==t.label&&(xC(o),Gg(o,t.label,n),o.setAttribute(Yg,t.label));let r=e.querySelector(`:scope > .${Jg}`),s=t.detail;s?(r||(r=y("span",Jg),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var CC={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"},wC=15e4,Ci={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 AC(e,t){let n=(e||"").trim().toLowerCase();if(n&&Ci[n])return Ci[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Ci[r])return Ci[r]}}return null}function wi(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){s(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var SC=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"]),TC=[{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=>SC.has(e)?"keyword":"plain"}];function Qg(e){return wi(e,TC)}var EC=[{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 MC(e){let t=wi(e,EC);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 kC=[{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 Zg(e){let t=wi(e,kC),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 LC=[{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 PC(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,p=e.slice(r,i);for(let c of wi(p,LC))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),b=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),f=b?r+b.index:o,x=e.slice(r,f),C=c==="script"?Qg(x):Zg(x);for(let S of C)t.push(S);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 RC(e,t){switch(t){case"html":return PC(e);case"css":return Zg(e);case"js":return Qg(e);case"json":return MC(e)}}function IC(e){let t=Uu(),n=y("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=CC[r];if(a){let i=y("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 Du(e,t,n){let o=e.length<=Iv?Wv(t,n):null,r=o?$v(e,o):[{type:"plain",value:e}];return jv(r)}function Xo(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(qa)):(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 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 E=oe(f.icon,16,"currentColor",1.5);E&&y.appendChild(E)}let C=document.createElement("span");C.textContent=f.label,y.appendChild(C),y.addEventListener("click",E=>{E.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 pt(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=oe(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 ho(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=oe(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 yo(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=pt({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 Xl(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=oe(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=Xo({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 Za="persona-artifact-custom-action-btn";function Mr(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 "+Za+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+Za+(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=ho({icon:e.icon,label:e.label,className:Za+(n?" persona-artifact-doc-copy-btn":"")}):o=pt({icon:e.icon,label:e.label,className:Za+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ls(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 Ou(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?Pn(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?go(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,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}:{}},P=Tr(E,C,"card");Jo(y,P,C)}else s&&Sr(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 P={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(P)){let M=Mr(W);M.setAttribute("data-artifact-custom-action",W.id),M.className=`${M.className} persona-flex-shrink-0`,c.append(M)}}catch{}}let E=ho({label:"Download",className:"persona-flex-shrink-0"});E.title=`Download ${r}`,E.setAttribute("data-download-artifact",s),c.append(E)}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:()=>Ou(e,t)});if(i)return i}return Ou(e,t)};var bo=new WeakMap;function Yl(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 ju(e){return bo.has(e)}function Uv(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 Nu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Pn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?go(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function zv(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 Fu=180,qv=240,Vv=.8,Kv=300,Gv=500,Jv="cubic-bezier(0.2, 0, 0, 1)",_u=240,Xv=.35;function Yv(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:Fu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let P of a)P.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let 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(Gv,Math.max(Kv,qv+p*Vv))),u=Math.round(c*Xv),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:_u,delay:u,easing:"ease-out",fill:"backwards"}):null,y=e.animate([{height:`${t}px`},{height:`${d}px`}],{duration:c,easing:Jv});e.style.height=`${d}px`;let C=!1,E=()=>{C||(C=!0,i(),r())};Promise.allSettled([y.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(c,u+_u)+120)},Fu)}function Qv(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 Rs="--persona-artifact-inline-body-height";function Zv(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 $u(e,t){let n=Uv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=Qv(o),d=o?.inlineActions??[],p=Zv(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=Z=>ei(zv(Z),t),C=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Rs),f.replaceChildren(y(Z)),bo.set(f,ce=>{f.replaceChildren(y(ce))})};if(c&&n.status==="complete")return C(n),f;let E=ti(n,{config:t.config,bodyLayout:p,resolveViewMode:()=>u??p.viewMode}),P=m("div","persona-artifact-inline-body");P.appendChild(E.el);let W=Z=>{let ce=Z.status!=="complete",Q=ce?p.streamingHeight:p.completeHeight,pe=typeof Q=="number";pe?f.style.setProperty(Rs,`${Q}px`):f.style.removeProperty(Rs);let ve=!!E.el.querySelector(".persona-code-pre"),he=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");P.classList.toggle("persona-artifact-content-flush",ve),P.classList.toggle("persona-artifact-inline-body--sized",pe&&he),P.classList.toggle("persona-artifact-inline-body--cap",!ce&&!he&&typeof p.completeHeight=="number")},M=n.status,k=(Z,ce)=>{M!=="complete"&&Z.status==="complete"?(typeof p.completeHeight=="number"?f.style.setProperty(Rs,`${p.completeHeight}px`):f.style.removeProperty(Rs),zu(P,ce?.suppressTransition?"none":p.transition,Z.id,()=>{E.update(Z),W(Z)})):E.update(Z),W(Z),M=Z.status};W(n);let F=p.overflow==="clip"&&a&&!!n.id;if(F&&(P.setAttribute("data-expand-artifact-inline",n.id),P.setAttribute("role","button"),P.setAttribute("tabindex","0"),P.classList.add("persona-cursor-pointer"),P.setAttribute("aria-label",`Open ${Nu(n).title} in panel`)),!r)return f.appendChild(P),bo.set(f,k),f;let z=m("div","persona-artifact-inline-chrome");z.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),U=m("span","persona-flex persona-items-center persona-flex-shrink-0"),q=oe("file-text",16,"currentColor",2);q&&U.appendChild(q);let ee=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");w.append(U,ee,D);let $=m("div","persona-artifact-inline-chrome-actions"),X=m("span","persona-flex persona-items-center persona-gap-1"),ye=()=>u??p.viewMode,be=i?yo({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:ye(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let ce=Z==="source"?"source":"rendered";ce!==ye()&&(u=ce,E.update(b),W(b))}}):null,He=s?pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;He&&n.id&&He.setAttribute("data-copy-artifact",n.id);let re=a?pt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;re&&n.id&&re.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(X),be&&$.appendChild(be.element),He&&$.appendChild(He),re&&$.appendChild(re),z.append(w,$),f.append(z,P);let me=Z=>{let{title:ce,typeLabel:Q}=Nu(Z);ee.textContent=ce,ee.title=ce,F&&P.setAttribute("aria-label",`Open ${ce} in panel`);let pe=Z.status!=="complete";if(pe){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let ve=Tr(Z,o,"inline-chrome");Jo(D,ve,o)}else Sr(Z.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Q;if(He&&He.classList.toggle("persona-hidden",pe),be){let ve=Z.artifactType==="markdown"?Z.file:void 0,he=!1;if(!pe&&ve&&p.viewMode!=="source"){let Ae=Ps(ve);Ae==="markdown"?he=!0:(Ae==="html"||Ae==="svg")&&(he=o?.filePreview?.enabled!==!1)}be.element.classList.toggle("persona-hidden",!he),be.setSelected(ye())}if(X.replaceChildren(),!pe&&d.length>0){let ve=Ls(Z);if(ve)for(let he of d)try{if(he.visible===void 0||he.visible(ve)){let Ae=Mr(he,{documentChrome:!0});Ae.setAttribute("data-artifact-custom-action",he.id),Ae.classList.add("persona-flex-shrink-0"),X.appendChild(Ae)}}catch{}}};return me(n),bo.set(f,(Z,ce)=>{if(c&&M!=="complete"&&Z.status==="complete"){let Q=f.isConnected?f.getBoundingClientRect().height:0;M="complete";let pe=Z,ve=!1,he=Ae=>{pe=Ae,ve=!0};bo.set(f,he),Yv(f,Q,{swap:()=>{C(pe),ve=!1,bo.set(f,he)},onSettled:()=>{ve?C(pe):bo.set(f,Ae=>{f.replaceChildren(y(Ae))})}});return}(Z.status!=="complete"||Z.id!==b.id)&&(u=null),b=Z,k(Z,ce),me(Z)}),f}var Uu=(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:()=>$u(e,t)});if(i)return i}return $u(e,t)};var Ql=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)})}},Ln=new Ql;Ln.register("PersonaArtifactCard",ei,{bubbleChrome:!1});Ln.register("PersonaArtifactInline",Uu,{bubbleChrome:!1});function Is(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Xa(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Zl=!1;function ex(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function zu(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"||Zl||s){o();return}Zl=!0;let a=ex(n);e.style.setProperty("view-transition-name",a);let i=()=>{Zl=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var tx="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",nx="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function ox(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 rx(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 sx=220;function ax(){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 ix(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 lx(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(Pu());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 cx(e,t,n,o,r,s){let a=null,i=0,d=!1,p=new Set,c=()=>{p.forEach(M=>clearTimeout(M)),p.clear()},u=(M,k)=>{let F=setTimeout(()=>{p.delete(F),M()},k);p.add(F)},b=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||d)return;let M=lx(r,s,o);a=M.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(M.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(b,sx))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):t.removeEventListener("load",W)},E=()=>{if(d||(d=!0,C(),c(),!a))return;let M=Math.max(0,o.minVisibleMs-(Date.now()-i));M>0?u(y,M):y()};function P(M){if(n===null)return;let k=M.data;!k||k.persona!=="artifact-preview-ready"||k.token!==n||M.source===t.contentWindow&&E()}function W(){let M=k=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>k()):setTimeout(k,0)};M(()=>M(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):t.addEventListener("load",W),()=>{d=!0,c(),C(),b()}}function ti(e,t){let{config:n}=t,o=t.registry??Ln,r=t.bodyLayout,s=n.markdown?hr(n.markdown):null,a=cs(n.sanitize),i=e,d=!1,p=re=>{let me=$n()!==null;s&&!me&&!d&&(d=!0,ls(()=>He(i)));let Z=s?s(re):jn(re);return s&&me&&a?a(Z):Z},c=m("div","persona-artifact-preview-body"),u=null,b=null,f=null,y=()=>{f&&(f(),f=null),u=null,b=null},C=null,E=null,P=null,W=!1,M=()=>{C=null,E=null,P=null,W=!1},k=null,F=null,z=()=>{k=null,F=null},w=40,U=0,q=re=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>re()):setTimeout(re,0),ee=re=>re.scrollHeight-re.clientHeight-re.scrollTop<=w,D=re=>{if(!r)return;let me=re.scrollHeight-re.clientHeight>1,Z=re.scrollHeight-re.clientHeight-re.scrollTop;re.classList.toggle("persona-artifact-fade-top",r.fadeTop&&me&&re.scrollTop>1),re.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&me&&Z>1)},$=re=>{U||(U=q(()=>{U=0,re.scrollTop=re.scrollHeight,D(re)}))},X=(re,me,Z,ce)=>{let Q=!!r,pe=Z.id+"|"+(Q?"w":"p");if(!C||P!==pe||C.parentElement!==c){y(),z(),c.replaceChildren();let Ae=m("pre",tx+" persona-code-pre"),at=m("code","persona-code");if(Ae.appendChild(at),Q){let Me=m("div","persona-artifact-source-window");if(Me.appendChild(Ae),c.appendChild(Me),!(r?.overflow==="clip")&&typeof Me.addEventListener=="function"){let Oe=()=>Me.scrollHeight-Me.clientHeight>1;Me.addEventListener("scroll",()=>{ee(Me)&&(W=!1),D(Me)},{passive:!0}),Me.addEventListener("wheel",ze=>{Oe()&&ze.deltaY<0&&(W=!0)},{passive:!0}),Me.addEventListener("touchmove",()=>{Oe()&&(W=!0)},{passive:!0})}C=Me}else c.appendChild(Ae),C=Ae;E=at,P=pe}let ve=Q?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",ce),ve.classList.toggle("persona-artifact-source-window--clip",ce&&r?.overflow==="clip"));let he=ve?ee(ve):!0;if(E.replaceChildren(Du(re,me?.language,me?.path)),ve){let Ae=Z.status!=="complete";ce&&Ae&&r?.followOutput&&!W&&he?$(ve):Ae||(W=!1),D(ve)}},ye=re=>{y(),M(),z(),c.replaceChildren();let me=m("div",nx);me.innerHTML=p(re),c.appendChild(me)},be=re=>{let me=re.id,Z=n.features?.artifacts,ce=Tr(re,Z,"status-body");if(k&&F===me&&k.parentElement===c){let ve=k.querySelector(".persona-artifact-status-view-text");ve&&Jo(ve,ce,Z);return}y(),M(),c.replaceChildren();let Q=m("div","persona-artifact-status-view"),pe=m("div","persona-artifact-status-view-text");Jo(pe,ce,Z),Q.appendChild(pe),c.appendChild(Q),k=Q,F=me},He=re=>{i=re;let me=t.resolveViewMode?.(re)??r?.viewMode??"rendered",Z=re.artifactType==="markdown"?re.file:void 0,ce=re.status!=="complete";ce||Sr(re.id);let Q=ce?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof Q=="number";if(r?.streamingView==="status"&&ce){be(re);return}if(Z){let he=Xa(re.markdown??""),Ae=Ps(Z),at=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&me==="rendered"&&at&&(Ae==="html"||Ae==="svg")){let Be=re.id+"\0"+he;if(u&&b===Be&&u.parentElement===c)return;M(),z(),y(),c.replaceChildren();let Oe=n.features?.artifacts?.filePreview,ze=Oe?.iframeSandbox??"allow-scripts";!Oe?.dangerouslyAllowSameOrigin&&ze.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."),ze=ze.split(/\s+/).filter(vt=>vt&&vt!=="allow-same-origin").join(" "));let Te=rx(Oe?.loading),le=m("div","persona-artifact-frame"),Pe=m("iframe","persona-artifact-iframe");Pe.setAttribute("sandbox",ze),Pe.setAttribute("data-artifact-id",re.id);let rt=null;Te.enabled&&Te.injectReadySignal?(rt=ax(),Pe.srcdoc=he+ix(rt)):Pe.srcdoc=he,le.appendChild(Pe),c.appendChild(le),Te.enabled&&(f=cx(le,Pe,rt,Te,re.id,n)),u=le,b=Be;return}if(y(),!ce&&Ae==="markdown"&&me==="rendered"){ye(he);return}X(he,{language:Z.language,path:Z.path},re,pe);return}if(re.artifactType==="markdown"){if(me==="source"){y(),X(re.markdown??"",void 0,re,pe);return}ye(re.markdown??"");return}y(),M(),z(),c.replaceChildren();let ve=re.component?o.get(re.component):void 0;if(ve){let Ae={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let at=ve(re.props??{},Ae);if(at){c.appendChild(at);return}}catch{}}c.appendChild(ox(re))};return He(e),{el:c,update(re){He(re)}}}import{Idiomorph as dx}from"idiomorph";var ni=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;dx.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 qu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ec={index:-1,draft:""};function Vu(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 Ku(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 Gu(){return new Map}function Ju(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Xu(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Yu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Qu(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 oi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Rn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function vo(e,t){return Rn(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 si(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 Zu(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 Ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},px=["pre","code","a","script","style"],ai=e=>({type:e?.type??Ws.type,placeholder:e?.placeholder??Ws.placeholder,speed:e?.speed??Ws.speed,duration:e?.duration??Ws.duration,buffer:e?.buffer??Ws.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"}],Hs=new Map;for(let e of of)Hs.set(e.name,e);var ux=e=>{Hs.set(e.name,e)},fx=e=>{of.some(t=>t.name===e)||Hs.delete(e)},gx=()=>Array.from(Hs.keys()),Er=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Hs.get(e)??null,ii=(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},mx=(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},hx=(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},tc=/\s/,yx=(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},bx=(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(tc.test(s[i])){let d=i;for(;d<s.length&&tc.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&&!tc.test(s[p]);)d.appendChild(mx(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),i=p}r.replaceChild(a,e)},vx=(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(hx(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},Bs=(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??px).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)yx(d,s)||i.push(d),d=a.nextNode();let p={value:o?.startIndex??0},c=t==="char"?bx:vx;for(let u of i)c(u,n,p);return r.innerHTML},li=(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},Ds=(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,xx=(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)},nc=new WeakMap,Cx=(e,t)=>{if(!e.onAttach)return;let n=nc.get(t);if(n||(n=new Map,nc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},rf=e=>{let t=nc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ci=(e,t)=>{xx(e,t),Cx(e,t)};function oc(e,t=Vt){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 Os=0,xo=null;function rc(e=document){if(Os++,Os===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;xo={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,Os=Math.max(0,Os-1),Os===0&&xo)){let n=e.body,o=e.defaultView??window;n.style.overflow=xo.originalOverflow,n.style.position=xo.originalPosition,n.style.top=xo.originalTop,n.style.width=xo.originalWidth,o.scrollTo(0,xo.scrollY),xo=null}}}var Ns={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ht=e=>(e?.launcher?.mountMode??"floating")==="docked",Co=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",sn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ns.side,width:t?.width??Ns.width,animate:t?.animate??Ns.animate,reveal:t?.reveal??Ns.reveal,maxHeight:t?.maxHeight??Ns.maxHeight}};var An={"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 wx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",di=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=wx,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=Ne("button",{className:zn("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||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=oe(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}},Ax="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pi=(e,t={})=>{let{wrapperClassName:n=Ax,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??"",E=a.tooltipText??"Clear chat",P=a.showTooltip??!0,W=m("div",n),M=!!(u||b),k=Ne("button",{className:zn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!M&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:p||Jt.actionIconColor,backgroundColor:c||void 0,border:M?`${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}}),F=oe(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:P}),{button:k,wrapper:W}};var Jt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},wo=e=>{let{config:t,showClose:n=!0}=e,o=Ne("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=Ne("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,z=oe(d,F*.6,"currentColor",1);z?p.replaceChildren(z):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let F=m("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=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ne("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),b=Ne("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.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",E=null,P=null;if(y){let z=pi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=z.button,P=z.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let W=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:M,wrapper:k}=di(t,{showClose:n,wrapperClassName:W});return a!=="top-right"&&o.appendChild(k),{header:o,iconHolder:p,headerTitle:u,headerSubtitle:b,closeButton:M,closeButtonWrapper:k,clearChatButton:E,clearChatButtonWrapper:P}},kr=(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 sf=e=>{let t=wo({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 Sx(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=oe(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=Xo({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 af=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=Xl({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,p.style.color=Jt.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=Jt.titleColor,c.textContent=a.title??"Chat Assistant",p.appendChild(c),Sx(p,r?.trailingActions,r?.onAction??s),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let M=r.onTitleClick;p.addEventListener("click",k=>{k.target.closest("button")||M()}),p.addEventListener("keydown",k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),M())})}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",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||Jt.actionIconColor;let y=a.closeButtonIconName??"x",C=oe(y,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f),i.appendChild(b);let E=m("div");E.style.display="none";let P=m("span");return P.style.display="none",{header:i,iconHolder:E,headerTitle:c,headerSubtitle:P,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},sc={default:sf,minimal:af},lf=e=>sc[e]??sc.default,Fs=(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=lf(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 ui=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}},fi=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=Ne("button",{className:zn("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}}),E=null,P=null;if(n){let k=parseFloat(u)||24,F=f?.trim()||"currentColor";r?(E=oe(r,k,F,2),E?C.appendChild(E):C.textContent=o):C.textContent=o,P=oe(s,k,F,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 W="send";return{button:C,wrapper:y,setMode:k=>{if(k===W)return;W=k;let F=k==="stop"?i:a;if(C.setAttribute("aria-label",F),n){if(E&&P){let z=k==="stop"?P:E;C.replaceChildren(z)}}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,b=m("div","persona-send-button-wrapper"),f=Ne("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=oe(i,p,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let E=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return _t({anchor:f,trigger:b,text:()=>f.getAttribute("aria-label")??E,enabled:P}),{button:f,wrapper:b}},mi=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??qn).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=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=oe(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}},hi=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},yi=()=>Ne("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var _s=e=>{let{config:t}=e,n=Ne("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=Ne("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}=ui(t);a();let i=fi(t),d=gi(t),p=mi(t),c=hi(t);p&&(p.previewsContainer.style.gap="8px",r.append(p.previewsContainer,p.input)),r.append(s);let u=Ne("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 cf=()=>{let e=Ne("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=oe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=oe("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},df=e=>{let{config:t}=e,n=Ne("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=yi(),r=hi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=ui(t);s.style.maxHeight="100px",a();let i=fi(t),d=gi(t),p=mi(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ne("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 pf=e=>{let t=e?.launcher?.enabled??!0,n=Ht(e);if(Co(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??Vt);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??Vt),{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&&An[r.position]?An[r.position]:An["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Vt);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??mn;return i.style.width=p,i.style.maxWidth=p,a.appendChild(i),{wrapper:a,panel:i}},Tx=(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}=di(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 k=pi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=k.button,i=k.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Ne("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Ne("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=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Ne("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 E=Ne("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),P=df({config:e}),{root:W,textNode:M}=cf();return n.append(d,r,p,E),i&&n.appendChild(i),{container:n,body:p,messagesWrapper:f,composerOverlay:E,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:d,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:W,peekTextNode:M}},uf=(e,t=!0)=>{if(Co(e))return Tx(e,t);let n=Ne("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?Fs(e,o,{showClose:t}):wo({config:e,showClose:t}),a=Ne("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=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),d=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),p=Ne("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Ht(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=_s({config:e}),y=e?.layout?.showFooter!==!1;r?kr(n,s,e):(s.header.style.display="none",kr(n,s,e)),n.append(a);let C=Ne("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 ac=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
|
|
31
|
+
`)),n=y("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function ef(e,t,n){let o=e.length<=wC?AC(t,n):null,r=o?RC(e,o):[{type:"plain",value:e}];return IC(r)}function mr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(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 S=document.createElement("hr");a.appendChild(S)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",f.id),f.destructive&&x.setAttribute("data-destructive",""),f.icon){let S=se(f.icon,16,"currentColor",1.5);S&&x.appendChild(S)}let C=document.createElement("span");C.textContent=f.label,x.appendChild(C),x.addEventListener("click",S=>{S.stopPropagation(),c(),n(f.id)}),a.appendChild(x)}let i=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=x=>{!a.contains(x.target)&&!o.contains(x.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function g(){a.classList.contains("persona-hidden")?d():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:g,destroy:b}}function lt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,p=y("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=se(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,g]of Object.entries(i))p.setAttribute(c,g);return p}function Lo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=y("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let b=se(t,s??14,"currentColor",2);b&&c.appendChild(b)}let g=y("span");if(g.textContent=n,c.appendChild(g),i&&c.addEventListener("click",i),p)for(let[b,f]of Object.entries(p))c.setAttribute(b,f);return c}function Po(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=y("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let g;c.icon?g=lt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(g=y("button","persona-icon-btn"+(c.className?" "+c.className:"")),g.type="button",g.setAttribute("aria-label",c.label),g.title=c.label,g.textContent=c.label,g.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),g.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:g}),s.appendChild(g)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Fc(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:p}=e,d=y("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=y("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let g=se(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let b=mr({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(b.element),d.addEventListener("click",f=>{f.stopPropagation();let x=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",x?"false":"true"),b.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),b.show()},close:()=>{d.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),d.remove()}}}var Ai="persona-artifact-custom-action-btn";function Xr(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 "+Ai+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+Ai+(n?" persona-artifact-doc-icon-btn":"");o=y("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=y("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Lo({icon:e.icon,label:e.label,className:Ai+(n?" persona-artifact-doc-copy-btn":"")}):o=lt({icon:e.icon,label:e.label,className:Ai+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function oa(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 tf(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?Nn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Mo(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 g=document.createElement("div");g.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-muted, #9ca3af)",g.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 x=document.createElement("div");if(x.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",x.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,S={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},M=Yr(S,C,"card");fr(x,M,C)}else s&&Jr(s),x.textContent=d;if(b.append(f,x),c.append(g,b),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let M={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let P of C)try{if(P.visible===void 0||P.visible(M)){let T=Xr(P);T.setAttribute("data-artifact-custom-action",P.id),T.className=`${T.className} persona-flex-shrink-0`,c.append(T)}}catch{}}let S=Lo({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),c.append(S)}return c}var Si=(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:()=>tf(e,t)});if(i)return i}return tf(e,t)};var Ro=new WeakMap;function _c(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 WC(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 nf(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Nn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Mo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function HC(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 of=180,BC=240,DC=.8,OC=300,NC=500,FC="cubic-bezier(0.2, 0, 0, 1)",rf=240,_C=.35;function $C(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:of,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let M of a)M.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(NC,Math.max(OC,BC+d*DC))),g=Math.round(c*_C),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:rf,delay:g,easing:"ease-out",fill:"backwards"}):null,x=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:FC});e.style.height=`${p}px`;let C=!1,S=()=>{C||(C=!0,i(),r())};Promise.allSettled([x.finished,f?.finished].filter(Boolean)).then(S),window.setTimeout(S,Math.max(c,g+rf)+120)},of)}function jC(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 ra="--persona-artifact-inline-body-height";function UC(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,g=t?.fadeMask;g===!0?(d=!0,c=!0):g===!1?(d=!1,c=!1):g&&typeof g=="object"?(d=g.top===!0,c=g.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!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:p,overflow:i,fadeTop:d,fadeBottom:c,transition:b,completeDisplay:f}}function sf(e,t){let n=WC(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=jC(o),p=o?.inlineActions??[],d=UC(o),c=d.completeDisplay==="card",g=null,b=n,f=y("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 x=Z=>Si(HC(Z),t),C=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(ra),f.replaceChildren(x(Z)),Ro.set(f,ue=>{f.replaceChildren(x(ue))})};if(c&&n.status==="complete")return C(n),f;let S=Ti(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>g??d.viewMode}),M=y("div","persona-artifact-inline-body");M.appendChild(S.el);let P=Z=>{let ue=Z.status!=="complete",te=ue?d.streamingHeight:d.completeHeight,fe=typeof te=="number";fe?f.style.setProperty(ra,`${te}px`):f.style.removeProperty(ra);let be=!!S.el.querySelector(".persona-code-pre"),he=!!S.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");M.classList.toggle("persona-artifact-content-flush",be),M.classList.toggle("persona-artifact-inline-body--sized",fe&&he),M.classList.toggle("persona-artifact-inline-body--cap",!ue&&!he&&typeof d.completeHeight=="number")},T=n.status,L=(Z,ue)=>{T!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(ra,`${d.completeHeight}px`):f.style.removeProperty(ra),cf(M,ue?.suppressTransition?"none":d.transition,Z.id,()=>{S.update(Z),P(Z)})):S.update(Z),P(Z),T=Z.status};P(n);let H=d.overflow==="clip"&&a&&!!n.id;if(H&&(M.setAttribute("data-expand-artifact-inline",n.id),M.setAttribute("role","button"),M.setAttribute("tabindex","0"),M.classList.add("persona-cursor-pointer"),M.setAttribute("aria-label",`Open ${nf(n).title} in panel`)),!r)return f.appendChild(M),Ro.set(f,L),f;let O=y("div","persona-artifact-inline-chrome");O.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let _=y("div","persona-artifact-inline-chrome-lead"),U=y("span","persona-flex persona-items-center persona-flex-shrink-0"),z=se("file-text",16,"currentColor",2);z&&U.appendChild(z);let Y=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),A=y("span","persona-artifact-inline-type");_.append(U,Y,A);let G=y("div","persona-artifact-inline-chrome-actions"),Q=y("span","persona-flex persona-items-center persona-gap-1"),le=()=>g??d.viewMode,J=i?Po({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:le(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let ue=Z==="source"?"source":"rendered";ue!==le()&&(g=ue,S.update(b),P(b))}}):null,me=s?lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;me&&n.id&&me.setAttribute("data-copy-artifact",n.id);let ee=a?lt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),J&&G.appendChild(J.element),me&&G.appendChild(me),ee&&G.appendChild(ee),O.append(_,G),f.append(O,M);let ye=Z=>{let{title:ue,typeLabel:te}=nf(Z);Y.textContent=ue,Y.title=ue,H&&M.setAttribute("aria-label",`Open ${ue} in panel`);let fe=Z.status!=="complete";if(fe){A.classList.contains("persona-artifact-inline-status")||(A.className="persona-artifact-inline-status",A.removeAttribute("data-preserve-animation"),A.replaceChildren());let be=Yr(Z,o,"inline-chrome");fr(A,be,o)}else Jr(Z.id),A.className="persona-artifact-inline-type",A.removeAttribute("data-preserve-animation"),A.replaceChildren(),A.textContent=te;if(me&&me.classList.toggle("persona-hidden",fe),J){let be=Z.artifactType==="markdown"?Z.file:void 0,he=!1;if(!fe&&be&&d.viewMode!=="source"){let Be=gr(be);Be==="markdown"?he=!0:(Be==="html"||Be==="svg")&&(he=o?.filePreview?.enabled!==!1)}J.element.classList.toggle("persona-hidden",!he),J.setSelected(le())}if(Q.replaceChildren(),!fe&&p.length>0){let be=oa(Z);if(be)for(let he of p)try{if(he.visible===void 0||he.visible(be)){let Be=Xr(he,{documentChrome:!0});Be.setAttribute("data-artifact-custom-action",he.id),Be.classList.add("persona-flex-shrink-0"),Q.appendChild(Be)}}catch{}}};return ye(n),Ro.set(f,(Z,ue)=>{if(c&&T!=="complete"&&Z.status==="complete"){let te=f.isConnected?f.getBoundingClientRect().height:0;T="complete";let fe=Z,be=!1,he=Be=>{fe=Be,be=!0};Ro.set(f,he),$C(f,te,{swap:()=>{C(fe),be=!1,Ro.set(f,he)},onSettled:()=>{be?C(fe):Ro.set(f,Be=>{f.replaceChildren(x(Be))})}});return}(Z.status!=="complete"||Z.id!==b.id)&&(g=null),b=Z,L(Z,ue),ye(Z)}),f}var lf=(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:()=>sf(e,t)});if(i)return i}return sf(e,t)};var $c=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)})}},Fn=new $c;Fn.register("PersonaArtifactCard",Si,{bubbleChrome:!1});Fn.register("PersonaArtifactInline",lf,{bubbleChrome:!1});function sa(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?xi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var jc=!1;function zC(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function cf(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"||jc||s){o();return}jc=!0;let a=zC(n);e.style.setProperty("view-transition-name",a);let i=()=>{jc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var qC="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",VC="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function KC(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=y("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 GC(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 JC=220;function YC(){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 XC(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 QC(e,t,n){let o=y("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=y("div","persona-artifact-frame-loading-indicator");r.appendChild(Kg());let s=null;return n.label!==!1&&(s=y("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 ZC(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(T=>clearTimeout(T)),d.clear()},g=(T,L)=>{let H=setTimeout(()=>{d.delete(H),T()},L);d.add(H)},b=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let T=QC(r,s,o);a=T.el,e.appendChild(a),i=Date.now(),o.label!==!1&&g(T.revealLabel,o.labelDelayMs)},x=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),g(b,JC))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",M):t.removeEventListener("load",P)},S=()=>{if(p||(p=!0,C(),c(),!a))return;let T=Math.max(0,o.minVisibleMs-(Date.now()-i));T>0?g(x,T):x()};function M(T){if(n===null)return;let L=T.data;!L||L.persona!=="artifact-preview-ready"||L.token!==n||T.source===t.contentWindow&&S()}function P(){let T=L=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>L()):setTimeout(L,0)};T(()=>T(()=>S()))}return g(f,o.delayMs),g(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",M):t.addEventListener("load",P),()=>{p=!0,c(),C(),b()}}function Ti(e,t){let{config:n}=t,o=t.registry??Fn,r=t.bodyLayout,s=n.markdown?_r(n.markdown):null,a=Os(n.sanitize),i=e,p=!1,d=ee=>{let ye=Zn()!==null;s&&!ye&&!p&&(p=!0,Ds(()=>me(i)));let Z=s?s(ee):eo(ee);return s&&ye&&a?a(Z):Z},c=y("div","persona-artifact-preview-body"),g=null,b=null,f=null,x=()=>{f&&(f(),f=null),g=null,b=null},C=null,S=null,M=null,P=!1,T=()=>{C=null,S=null,M=null,P=!1},L=null,H=null,O=()=>{L=null,H=null},_=40,U=0,z=ee=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ee()):setTimeout(ee,0),Y=ee=>ee.scrollHeight-ee.clientHeight-ee.scrollTop<=_,A=ee=>{if(!r)return;let ye=ee.scrollHeight-ee.clientHeight>1,Z=ee.scrollHeight-ee.clientHeight-ee.scrollTop;ee.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ye&&ee.scrollTop>1),ee.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ye&&Z>1)},G=ee=>{U||(U=z(()=>{U=0,ee.scrollTop=ee.scrollHeight,A(ee)}))},Q=(ee,ye,Z,ue)=>{let te=!!r,fe=Z.id+"|"+(te?"w":"p");if(!C||M!==fe||C.parentElement!==c){x(),O(),c.replaceChildren();let Be=y("pre",qC+" persona-code-pre"),rt=y("code","persona-code");if(Be.appendChild(rt),te){let $e=y("div","persona-artifact-source-window");if($e.appendChild(Be),c.appendChild($e),!(r?.overflow==="clip")&&typeof $e.addEventListener=="function"){let Le=()=>$e.scrollHeight-$e.clientHeight>1;$e.addEventListener("scroll",()=>{Y($e)&&(P=!1),A($e)},{passive:!0}),$e.addEventListener("wheel",_e=>{Le()&&_e.deltaY<0&&(P=!0)},{passive:!0}),$e.addEventListener("touchmove",()=>{Le()&&(P=!0)},{passive:!0})}C=$e}else c.appendChild(Be),C=Be;S=rt,M=fe}let be=te?C:null;be&&(be.classList.toggle("persona-artifact-source-window--fixed",ue),be.classList.toggle("persona-artifact-source-window--clip",ue&&r?.overflow==="clip"));let he=be?Y(be):!0;if(S.replaceChildren(ef(ee,ye?.language,ye?.path)),be){let Be=Z.status!=="complete";ue&&Be&&r?.followOutput&&!P&&he?G(be):Be||(P=!1),A(be)}},le=ee=>{x(),T(),O(),c.replaceChildren();let ye=y("div",VC);ye.innerHTML=d(ee),c.appendChild(ye)},J=ee=>{let ye=ee.id,Z=n.features?.artifacts,ue=Yr(ee,Z,"status-body");if(L&&H===ye&&L.parentElement===c){let be=L.querySelector(".persona-artifact-status-view-text");be&&fr(be,ue,Z);return}x(),T(),c.replaceChildren();let te=y("div","persona-artifact-status-view"),fe=y("div","persona-artifact-status-view-text");fr(fe,ue,Z),te.appendChild(fe),c.appendChild(te),L=te,H=ye},me=ee=>{i=ee;let ye=t.resolveViewMode?.(ee)??r?.viewMode??"rendered",Z=ee.artifactType==="markdown"?ee.file:void 0,ue=ee.status!=="complete";ue||Jr(ee.id);let te=ue?r?.streamingHeight:r?.completeHeight,fe=!!r&&typeof te=="number";if(r?.streamingView==="status"&&ue){J(ee);return}if(Z){let he=xi(ee.markdown??""),Be=gr(Z),rt=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ue&&ye==="rendered"&&rt&&(Be==="html"||Be==="svg")){let Ve=ee.id+"\0"+he;if(g&&b===Ve&&g.parentElement===c)return;T(),O(),x(),c.replaceChildren();let Le=n.features?.artifacts?.filePreview,_e=Le?.iframeSandbox??"allow-scripts";!Le?.dangerouslyAllowSameOrigin&&_e.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."),_e=_e.split(/\s+/).filter(et=>et&&et!=="allow-same-origin").join(" "));let we=GC(Le?.loading),ae=y("div","persona-artifact-frame"),Re=y("iframe","persona-artifact-iframe");Re.setAttribute("sandbox",_e),Re.setAttribute("data-artifact-id",ee.id);let ct=null;we.enabled&&we.injectReadySignal?(ct=YC(),Re.srcdoc=he+XC(ct)):Re.srcdoc=he,ae.appendChild(Re),c.appendChild(ae),we.enabled&&(f=ZC(ae,Re,ct,we,ee.id,n)),g=ae,b=Ve;return}if(x(),!ue&&Be==="markdown"&&ye==="rendered"){le(he);return}Q(he,{language:Z.language,path:Z.path},ee,fe);return}if(ee.artifactType==="markdown"){if(ye==="source"){x(),Q(ee.markdown??"",void 0,ee,fe);return}le(ee.markdown??"");return}x(),T(),O(),c.replaceChildren();let be=ee.component?o.get(ee.component):void 0;if(be){let Be={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let rt=be(ee.props??{},Be);if(rt){c.appendChild(rt);return}}catch{}}c.appendChild(KC(ee))};return me(e),{el:c,update(ee){me(ee)}}}import{Idiomorph as ew}from"idiomorph";var Ei=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ew.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 df=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Uc={index:-1,draft:""};function pf(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 uf(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 gf(){return new Map}function ff(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function mf(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function hf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function yf(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 Mi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function _n(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function oo(e,t){return _n(e)-e.scrollTop<=t}function ki(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Li(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 zc(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function vf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tw=["pre","code","a","script","style"],Pi=e=>({type:e?.type??aa.type,placeholder:e?.placeholder??aa.placeholder,speed:e?.speed??aa.speed,duration:e?.duration??aa.duration,buffer:e?.buffer??aa.buffer}),Cf=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],ia=new Map;for(let e of Cf)ia.set(e.name,e);var nw=e=>{ia.set(e.name,e)},ow=e=>{Cf.some(t=>t.name===e)||ia.delete(e)},rw=()=>Array.from(ia.keys()),Qr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ia.get(e)??null,Ri=(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},sw=(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},aw=(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},qc=/\s/,iw=(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},lw=(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(qc.test(s[i])){let p=i;for(;p<s.length&&qc.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<s.length&&!qc.test(s[d]);)p.appendChild(sw(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},cw=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(aw(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},la=(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??tw).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)iw(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?lw:cw;for(let g of i)c(g,n,d);return r.innerHTML},Ii=(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},ca=(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},xf=new WeakMap,dw=(e,t)=>{if(!e.styles)return;let n=xf.get(t);if(n||(n=new Set,xf.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)},Vc=new WeakMap,pw=(e,t)=>{if(!e.onAttach)return;let n=Vc.get(t);if(n||(n=new Map,Vc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},wf=e=>{let t=Vc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Wi=(e,t)=>{dw(e,t),pw(e,t)};function Kc(e,t=_t){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 da=0,Io=null;function Gc(e=document){if(da++,da===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Io={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,da=Math.max(0,da-1),da===0&&Io)){let n=e.body,o=e.defaultView??window;n.style.overflow=Io.originalOverflow,n.style.position=Io.originalPosition,n.style.top=Io.originalTop,n.style.width=Io.originalWidth,o.scrollTo(0,Io.scrollY),Io=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Mt=e=>(e?.launcher?.mountMode??"floating")==="docked",Wo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",cn=e=>{let t=e?.launcher?.dock;return{side:t?.side??pa.side,width:t?.width??pa.width,animate:t?.animate??pa.animate,reveal:t?.reveal??pa.reveal,maxHeight:t?.maxHeight??pa.maxHeight}};var Jc=e=>e==="followUp"?"follow-up":e,Yc=(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"}},uw=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'}},Af=new WeakSet,gw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,fw=e=>{gw()||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"})})},Xc=e=>{var P,T,L;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:i,plugins:p,chipsConfig:d,session:c,getTextarea:g,eventTarget:b}=e,f=o==="followUp",x=t.behavior,C=()=>{if(c.isStreaming())return;let H={suggestion:{...t},surface:o,source:r,behavior:x},O=b.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:H,bubbles:!0,composed:!0,cancelable:!0}));if(f&&b.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!O)return;for(let U of p)if(U.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:i})===!1)return;let _=g();if(x==="fill"){_.value=t.prompt,_.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),_.focus();return}_.value="",c.sendMessage(t.prompt)},S=()=>{let H=y("button",`persona-suggestion persona-suggestion--${s}`);if(H.type="button",H.disabled=a,H.dataset.suggestionId=t.id,H.dataset.emphasis=t.emphasis,H.dataset.behavior=x,s==="chip"&&(d?.fontFamily&&(H.style.fontFamily=uw(d.fontFamily)),d?.fontWeight&&(H.style.fontWeight=d.fontWeight),d?.paddingX&&(H.style.paddingLeft=d.paddingX,H.style.paddingRight=d.paddingX),d?.paddingY&&(H.style.paddingTop=d.paddingY,H.style.paddingBottom=d.paddingY)),t.icon){let _=se(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);_&&(_.classList.add("persona-suggestion__icon"),t.iconColor&&(_.style.color=t.iconColor),H.appendChild(_))}let O=y("span","persona-suggestion__copy");if(O.appendChild(Me("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&O.appendChild(Me("span",{className:"persona-suggestion__description",text:t.description})),H.appendChild(O),s!=="chip"){let _=se("arrow-right",16,"currentColor",1.8);_&&(_.classList.add("persona-suggestion__arrow"),H.appendChild(_))}return H.addEventListener("click",C),H},M=null;for(let H of p)if(H.renderSuggestion&&(M=H.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:i,defaultRenderer:S,select:C}),M))break;return M??(M=S()),(P=M.dataset).suggestionId||(P.suggestionId=t.id),(T=M.dataset).behavior||(T.behavior=x),(L=M.dataset).emphasis||(L.emphasis=t.emphasis),M instanceof HTMLButtonElement||M.setAttribute("aria-disabled",a?"true":"false"),M},ua=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 g=getComputedStyle(e).direction==="rtl",b=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),f=4,x=b<=f,C=b>=c-f,S=g?!C:!x,M=g?!x:!C;e.toggleAttribute("data-scroll-left",S),e.toggleAttribute("data-scroll-right",M)},i=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",i,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(i):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",i),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,g,b,f,x,C)=>{e.replaceChildren(),t.length=0,n.length=0;let S=C?.source??"config",M=C?.surface??(S==="config"?"starter":"followUp"),P=M==="followUp",T=C?.variant??"chip",L=C?.behavior??"send",H=C?.overflow??"wrap",O=C?.config??{},_=C?.plugins??[],U=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,z=P?"followUps":"starters";!Af.has(O)&&O.debug===!0&&T!=="chip"&&O.suggestions?.[z]?.overflow!==void 0&&(Af.add(O),console.info(`[persona] suggestions.${z}.overflow applies to the "chip" variant only; the "${T}" variant manages its own stacking.`));let Y=me=>me.map(Yc).filter(ee=>ee!==null).map(ee=>({...ee,behavior:ee.behavior??L})),A=Y(c??[]);_.forEach(me=>{me.transformSuggestions&&(A=Y(me.transformSuggestions({suggestions:A.map(ee=>({...ee})),surface:M,source:S,config:O})))});let G=U===void 0?A:A.slice(0,U);if(!G.length){e.hidden=!0,o=null,s();return}if(!P&&(f??g.getMessages()).some(ee=>ee.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Jc(M),e.dataset.variant=T,e.dataset.overflow=H;let Q=document.createDocumentFragment(),le=g.isStreaming();G.forEach((me,ee)=>{let ye=Xc({item:me,index:ee,surface:M,source:S,variant:T,streaming:le,config:O,plugins:_,chipsConfig:x,session:g,getTextarea:()=>b,eventTarget:e});Q.appendChild(ye),n.push(ye),[...ye instanceof HTMLButtonElement?[ye]:[],...Array.from(ye.querySelectorAll("button"))].forEach(ue=>{t.includes(ue)||(ue.disabled=le,t.push(ue))})}),e.appendChild(Q),a(),i();let J=JSON.stringify({normalized:G,surface:M,variant:T,source:S});J!==o&&(o=J,fw(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(me=>({...me})),surface:M,source:S,variant:T},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(me=>me.prompt)},bubbles:!0,composed:!0})))}}};var dn={"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 mw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Hi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=mw,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",p=y("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,g=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Me("button",{className:In("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Gt.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=se(g,s,"currentColor",1);return C?(C.style.display="block",x.appendChild(C)):x.textContent=b,p.appendChild(x),$t({anchor:x,trigger:p,text:()=>x.getAttribute("aria-label")??d,enabled:c}),{button:x,wrapper:p}},hw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Bi=(e,t={})=>{let{wrapperClassName:n=hw,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",g=a.borderWidth??"",b=a.borderColor??"",f=a.borderRadius??"",x=a.paddingX??"",C=a.paddingY??"",S=a.tooltipText??"Clear chat",M=a.showTooltip??!0,P=y("div",n),T=!!(g||b),L=Me("button",{className:In("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:d||Gt.actionIconColor,backgroundColor:c||void 0,border:T?`${g||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),H=se(p,r,"currentColor",1);return H&&(H.style.display="block",L.appendChild(H)),P.appendChild(L),$t({anchor:L,trigger:P,text:()=>L.getAttribute("aria-label")??S,enabled:M}),{button:L,wrapper:P}};var Gt={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))"},Qc={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},yw={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Ho=e=>{let{config:t,showClose:n=!0}=e,o=Me("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,p=r.headerIconName,d=Me("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let H=parseFloat(s)||24,O=se(p,H*.6,"currentColor",1);O?d.replaceChildren(O):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let H=y("img");H.src=t.launcher.iconUrl,H.alt="",H.className="persona-rounded-xl persona-object-cover",H.style.height=s,H.style.width=s,d.replaceChildren(H)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Me("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Gt.titleColor,...Qc}}),b=Me("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Gt.subtitleColor,...yw}});c.append(g,b),i?o.append(c):o.append(d,c);let f=r.clearChat??{},x=f.enabled??!0,C=f.placement??"inline",S=null,M=null;if(x){let O=Bi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=O.button,M=O.wrapper,C==="top-right"&&(M.style.right="48px"),C==="inline"&&o.appendChild(M)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&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:T,wrapper:L}=Hi(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&o.appendChild(L),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:b,closeButton:T,closeButtonWrapper:L,clearChatButton:S,clearChatButtonWrapper:M}},Zr=(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 Sf=e=>{let t=Ho({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 bw(e,t,n){if(t?.length)for(let o of t){let r=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Gt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=se(o.icon,16,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=y("div","persona-relative");s.appendChild(r);let a=mr({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-right"});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 Tf=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Fc({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Gt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=y("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Gt.titleColor,Object.assign(c.style,Qc),c.textContent=a.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let L=r.onTitleClick;d.addEventListener("click",H=>{H.target.closest("button")||L()}),d.addEventListener("keydown",H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),L())})}let T=r?.titleRowHover;T&&(d.style.borderRadius=T.borderRadius??"10px",d.style.padding=T.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=T.background??"",d.style.borderColor=T.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=a.closeButtonSize??"32px",b=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=g,f.style.width=g,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Gt.actionIconColor;let x=a.closeButtonIconName??"x",C=se(x,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f);let S=y("div","persona-flex persona-items-center persona-gap-1");p||bw(S,r?.trailingActions,r?.onAction??s),S.appendChild(b),i.appendChild(S);let M=y("div");M.style.display="none";let P=y("span");return P.style.display="none",{header:i,iconHolder:M,headerTitle:c,headerSubtitle:P,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},Zc={default:Sf,minimal:Tf},Ef=e=>Zc[e]??Zc.default,ga=(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=y("div");i.style.display="none";let p=y("span"),d=y("span"),c=y("button");c.style.display="none";let g=y("div");return g.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Ef(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 Di=e=>{let t=y("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 p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let d=p.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let p=t.style.maxHeight;if(p!==s){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},i=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,a());t.style.height=`${p}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}},Oi=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,g=t.size??"40px",b=t.backgroundColor,f=t.textColor,x=y("div","persona-send-button-wrapper"),C=Me("button",{className:In("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?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g: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: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}}),S=null,M=null;if(n){let L=parseFloat(t.iconSize??"")||Math.round((parseFloat(g)||24)*.5),H=t.iconStrokeWidth??2,O=f?.trim()||"currentColor";r?(S=se(r,L,O,H),S?C.appendChild(S):C.textContent=o):C.textContent=o,M=se(s,L,O,H)}else C.textContent=p;C.setAttribute("aria-label",a),x.appendChild(C),$t({anchor:C,trigger:x,text:()=>C.getAttribute("aria-label")??"",enabled:c});let P="send";return{button:C,wrapper:x,setMode:L=>{if(L===P)return;P=L;let H=L==="stop"?i:a;if(C.setAttribute("aria-label",H),n){if(S&&M){let O=L==="stop"?M:S;C.replaceChildren(O)}}else C.textContent=L==="stop"?d:p}}},Ni=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,b=y("div","persona-send-button-wrapper"),f=Me("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:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:g||"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=se(i,d,g||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let S=t.tooltipText??"Start voice recognition",M=t.showTooltip??!1;return $t({anchor:f,trigger:b,text:()=>f.getAttribute("aria-label")??S,enabled:M}),{button:f,wrapper:b}},Fi=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=y("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=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??no).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=y("div","persona-send-button-wrapper"),c=Me("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"}}),g=se(s,p,"currentColor",1.5);g?c.appendChild(g):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),d.appendChild(c);let b=t.buttonTooltipText??"Attach file";return $t({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:d,input:r,previewsContainer:o}},_i=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=y("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=y("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},$i=()=>Me("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var es=e=>{let{config:t}=e,n=Me("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=$i(),r=Me("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}=Di(t);a();let i=Oi(t),p=Ni(t),d=Fi(t),c=_i(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let g=Me("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&b.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),g.append(b,f),r.append(g),r.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:b,rightActions:f,setSendButtonMode:i.setMode}};var Mf=()=>{let e=Me("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=se("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),s=se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ji=e=>{let{config:t}=e,n=Me("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=$i(),r=_i(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Di(t);s.style.maxHeight="100px",a();let i=Oi(t),p=Ni(t),d=Fi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Me("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=y("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let b=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(i.wrapper),c.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(g,s,b),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:g,rightActions:b,setSendButtonMode:i.setMode}};var vw=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}},xw=(e,t)=>{if(!e)return null;let n=vw(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Cw=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},ww=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ed=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(":"))},td=320,Rf=320,Aw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Sw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Tw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ew=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Mw=e=>{if(!e||e.length===0)return null;let t=Me("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Me("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=y("span","persona-mention-chip-icon"),s=se(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Me("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},kw=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Zs(o.ref,{readonly:!0,render:t}))}return n},kf="\uE000",Lf="\uE001",Lw=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${kf}${r}:${b}${Lf}`,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(kw(t,o));return}e.innerHTML=i;let d=new RegExp(`${kf}${r}:(\\d+)${Lf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let b=c.nextNode();b;b=c.nextNode())g.push(b);for(let b of g){let f=b;for(let x=d.exec(f.data);x;x=d.exec(f.data)){let C=t[Number(x[1])],S=f.splitText(x.index);S.data=S.data.slice(x[0].length),C?.kind==="mention"&&S.parentNode?.insertBefore(Zs(C.ref,{readonly:!0,render:o}),S),f=S}}},Pw=(e,t,n)=>{if(e.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=y("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${td}px`,d.style.maxHeight=`${Rf}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),ww(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Rw=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!ed(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${td}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Iw=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!ed(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${td}px`,r.style.maxHeight=`${Rf}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}},Ww=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!ed(o.data))return;let r=y("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}},ts=()=>{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},If=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:ts};if(t){let r=t(o);if(r!==null)return r}return ts()},Hw=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("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},Pf=(e,t,n="div")=>{let o=y(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},fa=(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},Wf=(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 x=y("div");return x.style.display="none",x.id=`actions-${e.id}`,x.setAttribute("data-actions-for",e.id),x}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],b=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let f=(x,C,S)=>{let M=lt({icon:x,label:C,size:14,className:"persona-message-action-btn"});return M.setAttribute("data-action",S),M};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},ma=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,g=d?.show??!1,b=p?.position??"left",f=d?.position??"below",x=fa(e.role,i),C=y("div",x.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 S=Aw(e),M=e.content?.trim()??"",T=S.length>0&&M===ci,L=Pi(s?.widgetConfig?.features?.streamAnimation),H=s?.widgetConfig?.features?.streamAnimation?.plugins,O=e.role==="assistant"&&L.type!=="none"?Qr(L.type,H):null,_=e.role==="assistant"&&O?.isAnimating?.(e)===!0,U=e.role==="assistant"&&O!==null&&(!!e.streaming||_);U&&O?.bubbleClass&&C.classList.add(O.bubbleClass);let z=document.createElement("div");z.classList.add("persona-message-content"),e.streaming&&z.classList.add("persona-content-streaming"),U&&O&&(O.containerClass&&z.classList.add(O.containerClass),z.style.setProperty("--persona-stream-step",`${L.speed}ms`),z.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let Y=U?Ri(e.content??"",L.buffer,O,e,!!e.streaming):e.content??"",A=()=>{let te=t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent});return U&&O?.wrap==="char"?la(te,"char",e.id,{skipTags:O.skipTags}):U&&O?.wrap==="word"?la(te,"word",e.id,{skipTags:O.skipTags}):te},G=null;if(T?(G=document.createElement("div"),G.innerHTML=A(),G.style.display="none",z.appendChild(G)):e.contentSegments?.length?Lw(z,e.contentSegments,te=>t({text:te,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):z.innerHTML=A(),U&&O?.useCaret&&!T&&M){let te=Ii(),fe=z.querySelectorAll(".persona-stream-char, .persona-stream-word"),be=fe[fe.length-1];if(be?.parentNode)be.parentNode.insertBefore(te,be.nextSibling);else{let he=z.lastElementChild;he?he.appendChild(te):z.appendChild(te)}}if(g&&f==="inline"&&e.createdAt){let te=Pf(e,d,"span");te.classList.add("persona-timestamp-inline");let fe=z.lastElementChild;fe?fe.appendChild(te):z.appendChild(te)}if(S.length>0){let te=Pw(S,!T&&!!M,()=>{T&&G&&(G.style.display="")});te?C.appendChild(te):T&&G&&(G.style.display="")}let Q=Sw(e);if(Q.length>0){let te=Rw(Q);te&&C.appendChild(te)}let le=Tw(e);if(le.length>0){let te=Iw(le);te&&C.appendChild(te)}let J=Ew(e);if(J.length>0){let te=Ww(J);te&&C.appendChild(te)}let me=e.contentSegments?.length?null:Mw(e.contextMentions);if(me&&C.appendChild(me),C.appendChild(z),g&&f==="below"&&e.createdAt){let te=Pf(e,d);te.classList.add("persona-mt-1"),C.appendChild(te)}let ee=e.role==="assistant"?xw(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let te=!!(Y&&Y.trim()),fe=L.placeholder==="skeleton",be=fe&&L.buffer==="line"&&te;if(te)be&&C.appendChild(ca());else if(fe)C.appendChild(ca());else{let he=If("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(ee&&e.stopReason&&!e.streaming&&(M||(z.style.display="none"),C.appendChild(Cw(e.stopReason,ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let te=Wf(e,o,r);C.appendChild(te)}if(!c||e.role==="system")return C;let Z=y("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=Hw(p,e.role);return b==="right"||b==="left"&&e.role==="user"?Z.append(C,ue):Z.append(ue,C),Z},Bw=(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}):ma(e,t,n,o,r,s)};var Dw=40,Ow=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=se(t.name,Dw);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Me("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Me("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Hf=(e,t,n={})=>{let o=Me("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=y("h2","persona-welcome-title"),s=y("p","persona-welcome-subtitle");return{host:Me("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},ns=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},zi=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Ow(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Nw="data-persona-welcome-plugin",Bf="data-persona-welcome-overlay",Ui="persona-welcome-overlay-active",nd=new WeakMap,Df=(e,t,n)=>{n.setAttribute(Nw,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Bf,""),e.classList.contains(Ui)||(nd.set(e,e.scrollTop),e.classList.add(Ui),e.scrollTop=0)},Of=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Bf),e.classList.contains(Ui)&&(e.classList.remove(Ui),e.scrollTop=nd.get(e)??e.scrollTop,nd.delete(e))},Nf=()=>{let e=Me("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},qi=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Me("div",{className:fa("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Me("div",{className:"persona-flex"},r)),e.hidden=!1},Fw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Ff=(e,t)=>{if(Fw()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var _w="Hello \u{1F44B}",$w="I can answer questions and help you get things done here.",_f=new WeakSet,Cn=(e,t)=>!!e&&e[t]!==void 0,jw=(e,t)=>{!e||e.debug!==!0||!t.length||_f.has(e)||(_f.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Bo=e=>{let t=e?.welcome,n=e?.copy,o=Cn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Cn(t,"dismiss")?t.dismiss:"never",s=[];return Cn(t,"title")&&Cn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Cn(t,"subtitle")&&Cn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Cn(t,"variant")&&Cn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Cn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Cn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),jw(e,s),{title:Cn(t,"title")?t.title:n?.welcomeTitle??_w,subtitle:Cn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??$w,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},hr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var $f=e=>{let t=e?.launcher?.enabled??!0,n=Mt(e);if(Wo(e)){let c=e?.launcher?.composerBar??{},g=y("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??_t);let b=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",g.appendChild(b);let f=y("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??_t),{wrapper:g,panel:b,pillRoot:f}}if(n){let c=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(g),{wrapper:c,panel:g}}if(!t){let c=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=y("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,g.style.width="100%",c.appendChild(g),{wrapper:c,panel:g}}let r=e?.launcher??{},s=r.position&&dn[r.position]?dn[r.position]:dn["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??_t);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??xn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},od=e=>{let t=Me("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Jc(e)}});return t.hidden=!0,t},jf=(e,t)=>{let n=od("starter"),o=Hf(e,n,{flatShadow:Mt(e)}),r=Bo(e);zi(o,r),ns(t,o.host,hr(r,e?.initialMessages));let s=Nf();return qi(s,r.message,e),{welcome:o,greetingHost:s}},Uw=(e,t)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Hi(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 _=Bi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=_.button,i=_.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=Me("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Me("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:g}=jf(e,d),{host:b,title:f,subtitle:x}=c,C=c.starterSuggestions,S=y("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),M=od("followUp"),P=Eo(e,!0);P&&(S.style.maxWidth=P,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),d.append(b,g,S,M);let T=Me("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=ji({config:e}),{root:H,textNode:O}=Mf();return n.append(p,r,d,T),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:M,composerOverlay:T,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,welcomeHost:b,welcomeIconHolder:c.iconHolder,greetingHost:g,introTitle:f,introSubtitle:x,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,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:O}},Uf=(e,t=!0)=>{if(Wo(e))return Uw(e,t);let n=Me("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?ga(e,o,{showClose:t}):Ho({config:e,showClose:t}),a=Me("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{welcome:i,greetingHost:p}=jf(e,a),{host:d,title:c,subtitle:g}=i,b=i.starterSuggestions,f=y("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=od("followUp"),C=Eo(e,!1);C&&(f.style.maxWidth=C,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),a.append(d,p,f,x);let S=es({config:e}),M=e?.layout?.showFooter!==!1;r?Zr(n,s,e):(s.header.style.display="none",Zr(n,s,e)),n.append(a);let P=Me("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 M||(S.footer.style.display="none"),n.append(S.footer),n.append(P),{container:n,body:a,messagesWrapper:f,starterSuggestions:b,transcriptSuggestions:x,composerOverlay:P,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:d,welcomeIconHolder:i.iconHolder,greetingHost:p,introTitle:c,introSubtitle:g,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:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};var rd=(e,t)=>{let n=y("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 As=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=Ht(s),d=n.querySelector("[data-role='launcher-title']");if(d){let M=a.title??"Chat Assistant";d.textContent=M,d.setAttribute("title",M)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let M=a.subtitle??"Here to help you get answers fast";p.textContent=M,p.setAttribute("title",M)}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 M=a.agentIconSize??"40px";if(u.style.height=M,u.style.width=M,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(M)||24,F=oe(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 b=n.querySelector("[data-role='launcher-image']");if(b){let M=a.agentIconSize??"40px";b.style.height=M,b.style.width=M,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 M=a.callToActionIconSize??"32px";f.style.height=M,f.style.width=M,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(M)||24,z=Math.max(F-k,8),w=oe(a.callToActionIconName,z,"currentColor",2);w?f.appendChild(w):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&An[a.position]?An[a.position]:An["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} ${y}`,i||(n.style.zIndex=String(a.zIndex??Vt));let P="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??P,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}=pf(e),s=uf(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}}},ic=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>ac(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=ac(e,n);return{instance:r,element:r.element}};var Mx=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}},Ex=(e,t)=>{if(!e)return null;let n=Mx(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},kx=(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},Px=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},lc=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},cc=320,yf=320,Lx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Rx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ix=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Wx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Hx=e=>{if(!e||e.length===0)return null;let t=Ne("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ne("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=oe(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ne("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Bx=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ts(o.ref,{readonly:!0,render:t}))}return n},gf="\uE000",mf="\uE001",Dx=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${gf}${r}:${b}${mf}`,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(Bx(t,o));return}e.innerHTML=i;let p=new RegExp(`${gf}${r}:(\\d+)${mf}`),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])],E=f.splitText(y.index);E.data=E.data.slice(y[0].length),C?.kind==="mention"&&E.parentNode?.insertBefore(Ts(C.ref,{readonly:!0,render:o}),E),f=E}}},Ox=(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=`${cc}px`,p.style.maxHeight=`${yf}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}),Px(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}},Nx=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(!lc(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=`${cc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Fx=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(!lc(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=`${cc}px`,r.style.maxHeight=`${yf}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}},_x=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(!lc(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}},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},bf=(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()},$x=(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},hf=(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},dc=(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},vf=(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,E)=>{let P=pt({icon:y,label:C,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",E),P};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},$s=(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=dc(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 E=Lx(e),P=e.content?.trim()??"",M=E.length>0&&P===Fa,k=ai(s?.widgetConfig?.features?.streamAnimation),F=s?.widgetConfig?.features?.streamAnimation?.plugins,z=e.role==="assistant"&&k.type!=="none"?Er(k.type,F):null,w=e.role==="assistant"&&z?.isAnimating?.(e)===!0,U=e.role==="assistant"&&z!==null&&(!!e.streaming||w);U&&z?.bubbleClass&&C.classList.add(z.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),U&&z&&(z.containerClass&&q.classList.add(z.containerClass),q.style.setProperty("--persona-stream-step",`${k.speed}ms`),q.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let ee=U?ii(e.content??"",k.buffer,z,e,!!e.streaming):e.content??"",D=()=>{let Q=t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent});return U&&z?.wrap==="char"?Bs(Q,"char",e.id,{skipTags:z.skipTags}):U&&z?.wrap==="word"?Bs(Q,"word",e.id,{skipTags:z.skipTags}):Q},$=null;if(M?($=document.createElement("div"),$.innerHTML=D(),$.style.display="none",q.appendChild($)):e.contentSegments?.length?Dx(q,e.contentSegments,Q=>t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=D(),U&&z?.useCaret&&!M&&P){let Q=li(),pe=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=pe[pe.length-1];if(ve?.parentNode)ve.parentNode.insertBefore(Q,ve.nextSibling);else{let he=q.lastElementChild;he?he.appendChild(Q):q.appendChild(Q)}}if(u&&f==="inline"&&e.createdAt){let Q=hf(e,p,"span");Q.classList.add("persona-timestamp-inline");let pe=q.lastElementChild;pe?pe.appendChild(Q):q.appendChild(Q)}if(E.length>0){let Q=Ox(E,!M&&!!P,()=>{M&&$&&($.style.display="")});Q?C.appendChild(Q):M&&$&&($.style.display="")}let X=Rx(e);if(X.length>0){let Q=Nx(X);Q&&C.appendChild(Q)}let ye=Ix(e);if(ye.length>0){let Q=Fx(ye);Q&&C.appendChild(Q)}let be=Wx(e);if(be.length>0){let Q=_x(be);Q&&C.appendChild(Q)}let He=e.contentSegments?.length?null:Hx(e.contextMentions);if(He&&C.appendChild(He),C.appendChild(q),u&&f==="below"&&e.createdAt){let Q=hf(e,p);Q.classList.add("persona-mt-1"),C.appendChild(Q)}let re=e.role==="assistant"?Ex(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(ee&&ee.trim()),pe=k.placeholder==="skeleton",ve=pe&&k.buffer==="line"&&Q;if(Q)ve&&C.appendChild(Ds());else if(pe)C.appendChild(Ds());else{let he=bf("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(re&&e.stopReason&&!e.streaming&&(P||(q.style.display="none"),C.appendChild(kx(e.stopReason,re))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Q=vf(e,o,r);C.appendChild(Q)}if(!c||e.role==="system")return C;let Z=m("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ce=$x(d,e.role);return b==="right"||b==="left"&&e.role==="user"?Z.append(C,ce):Z.append(ce,C),Z},jx=(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}):$s(e,t,n,o,r,s)};var Lr=new Set,Ux=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zx=(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
|
-
`):""},uc=(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)"},Kx=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Vx(e,o?.previewMaxLines??3),a=n?Kp(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=El(n,d.activeTextTemplate,p):!i&&d.completeTextTemplate&&(p=El(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:i}},Cf=(e,t,n)=>{let o=Rr.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=oe(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")},fc=(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&&Rr.has(e.id),{summary:d,previewText:p,isActive:c}=Kx(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 D=m("span","");return D.setAttribute("data-tool-elapsed",y),D.textContent=bs(n),D},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:bs(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(f.textContent=E,b.appendChild(f)):E instanceof HTMLElement?b.appendChild(E):(f.textContent=d,b.appendChild(f));let P=s.loadingAnimation??"none",W=o.activeTextTemplate,M=o.completeTextTemplate,k=c?W:M,F=E instanceof HTMLElement,z=(D,$)=>{f.textContent="";let X=n.name?.trim()||"tool",ye=Oa(D,X),be=0;for(let He of ye){let re=He.styles.length>0?(()=>{let me=m("span",He.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(me),me})():f;if(He.isDuration&&c)re.appendChild(C());else{let me=He.isDuration?bs(n):He.text;$?be=mo(re,me,be):re.appendChild(document.createTextNode(me))}}};if(!F)if(c&&P!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),P==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),k&&z(k,!1);else if(f.classList.add(`persona-tool-loading-${P}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),k)z(k,!0);else{let $=f.textContent||d;f.textContent="",mo(f,$,0)}}else k&&z(k,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=oe(i?"chevron-up":"chevron-down",16,D,2);$?w.appendChild($):w.textContent=i?"Hide":"Show";let X=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(w),u.append(b,X)}else u.append(b);let U=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&p){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:c,config:t??{}});qx(U,D)||(U.textContent=p),U.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,U),r;let q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=i?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,q.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",uc(X,o),X.textContent=uo(n.args),D.append($,X),q.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",uc(X,o),X.textContent=n.chunks.join(""),D.append($,X),q.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",uc(X,o),X.textContent=uo(n.result),D.append($,X),q.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,q.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=oe(i?"chevron-up":"chevron-down",16,D,2);$?w.appendChild($):w.textContent=i?"Hide":"Show"}q.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(u,U,q),r};var Yo=new Map,bi=e=>{let n=(e.startsWith(En)?e.slice(En.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 Yo.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=oe(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 vi=(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=oe(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(En)?ps(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}:{}}),P=!n.toolName,W=E||(P?n.description:`The assistant wants to use \u201C${C??bi(n.toolName)}\u201D.`),M=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(M.style.color=o.descriptionColor),M.textContent=W,u.appendChild(M),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 U=m("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(U),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let k=o?.detailsDisplay??"collapsed",F=!!n.description&&!P,z=F||!!n.parameters;if(k!=="hidden"&&z){let w=Af(e.id,t),U=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");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span");q.setAttribute("data-approval-details-label","true");let ee=m("span","persona-inline-flex persona-items-center");ee.setAttribute("data-approval-details-chevron","true"),U.append(q,ee),Sf(U,w,t),u.appendChild(U);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=w?"":"none",F){let $=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,D.appendChild($)}if(n.parameters){let $=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&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=uo(n.parameters),D.appendChild($)}u.appendChild(D)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let U=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");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let q=oe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",U.appendChild(q));let ee=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(ee);let D=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");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let $=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",D.appendChild($));let X=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(X),w.append(U,D),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function Gx(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??Gx(t),b=!1,f=null,y=()=>{if(!b)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let W=n.getBoundingClientRect(),M=i?.()??null,k=M!=null?P.top+M:P.top,F=o==="top-start"||o==="top-end"?k-r-W.height:P.bottom+r,w=o==="bottom-end"||o==="top-end"?P.right-W.width:P.left,U=a?.()??null;if(U!=null){let q=Math.max(P.left,P.right-W.width);w=Math.min(Math.max(P.left+U,P.left),q)}n.style.top=`${F}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},E=()=>{if(b)return;b=!0,d!=null&&(n.style.zIndex=String(d)),u.appendChild(n),y();let P=(t.ownerDocument??document).defaultView??window,W=t.ownerDocument??document,M=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}y()},k=z=>{let w=typeof z.composedPath=="function"?z.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},F=P.setTimeout(()=>{W.addEventListener("pointerdown",k,!0)},0);P.addEventListener("scroll",M,!0),P.addEventListener("resize",M),f=()=>{P.clearTimeout(F),W.removeEventListener("pointerdown",k,!0),P.removeEventListener("scroll",M,!0),P.removeEventListener("resize",M)},p?.()};return{get isOpen(){return b},open:E,close:C,toggle:()=>b?C():E(),reposition:y,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 Jx=()=>({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))},Qo=(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)},Xx=e=>e?.approval!==!1?e?.approval:void 0,Yx=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Yo.get(e)??n==="expanded"},gc=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Qx=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(En)?ps(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??bi(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},Zx=e=>{let t=m("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?bi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},eC=(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&&Yx(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 E=m("span","persona-approval-logo"),P=oe("shield-check",16,"currentColor",2);P&&E.appendChild(P),C.appendChild(E);let W=Qx(n,o);if(u){let U=m("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let q=oe("chevron-down",14,"currentColor",2);q&&U.appendChild(q),W.append(" "),W.appendChild(U)}C.appendChild(W),i.appendChild(C);let M=m("div","persona-approval-body");if(u){let U=m("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!b,p){let q=m("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,U.appendChild(q)}if(c){let q=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=uo(n.parameters),U.appendChild(q)}M.appendChild(U)}if(n.reason){let U=m("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(q,document.createTextNode(n.reason)),M.appendChild(U)}let k=m("div","persona-approval-actions"),F=null,z=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.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 U=m("div","persona-approval-split"),q=m("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),z(q),q.append(o?.approveLabel??"Always allow",gc("\u23CE"));let ee=m("button","persona-approval-caret");ee.type="button",ee.setAttribute("data-action","toggle-menu"),ee.setAttribute("aria-label","More options"),z(ee);let D=oe("chevron-down",15,"currentColor",2);D&&ee.appendChild(D),U.append(q,ee),k.append(U,w),w.append(gc("Esc"));let $=m("div","persona-approval-menu"),X=m("button","persona-approval-menu-item");X.type="button",X.append("Allow once",gc("\u2318\u23CE")),$.appendChild(X),F=Mf({anchor:U,content:$,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,F),X.addEventListener("click",()=>{Qo(e,t.id),r()})}else{let U=m("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),z(U),U.append(o?.approveLabel??"Allow"),k.append(U,w)}return M.appendChild(k),i.appendChild(M),i.addEventListener("click",U=>{let q=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!q)return;let ee=q.getAttribute("data-action");if(ee==="toggle-params"){let D=i.querySelector('[data-role="params"]');if(D){let $=D.hidden;D.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?y:f),Yo.set(t.id,$)}return}if(ee==="toggle-menu"){F?.toggle();return}if(ee==="always"){Qo(e,t.id),r({remember:!0});return}if(ee==="allow"){Qo(e,t.id),r();return}if(ee==="deny"){Qo(e,t.id),s();return}}),i},Pf=()=>{let e=Jx();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=Xx(a);if(i.status!=="pending"){if(Qo(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Zx(i)}kf(e,o.id);let p=d?.enableAlwaysAllow===!0,c=eC(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=>{Ef(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),Qo(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()])Qo(e,o);e.latestPendingApprovalId=null}}};var Lf=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(E=>E.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 js=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 Us=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 tC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),nC=new Set(["step_start","execution_start"]),oC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),rC=new Set(["step_complete","agent_turn_complete"]),sC=new Set(["flow_complete","agent_complete"]),Rf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Zo=(e,t)=>{let n=e[t];return Wf(n)?n:void 0};function mc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function xi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function aC(e,t){return typeof t.type=="string"?t.type:e}function iC(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 lC(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 If(e){let t=Zo(e,"result"),n=[Zo(e,"tokens"),Zo(e,"totalTokens"),t?Zo(t,"tokens"):void 0,Zo(e,"usage"),t?Zo(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function cC(e){let t=Zo(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function dC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var zs=class{constructor(t=dC){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:xi(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(!Wf(n)){Rf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=aC(t,n),r=this.now();if(tC.has(o)){this.startRun(r);return}if(nC.has(o)){this.run||this.startRun(r);return}if(oC.has(o)){if(!lC(o,n))return;let s=iC(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+mc(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:xi(i,d),outputTokens:i,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(rC.has(o)){if(!this.run)return;let s=this.run,a=If(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,d=s.exactOutputTokens+mc(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:xi(d,p),outputTokens:d,durationMs:p,source:i?"usage":"estimate"};return}if(sC.has(o)){if(!this.run)return;let s=this.run,a=If(n),i=a??s.exactOutputTokens+mc(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:xi(i,p),outputTokens:i,durationMs:p,source:d},this.run=null;return}if(Rf.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:cC(n)??o-t.startedAt}};function Ir(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var pC={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)"}},uC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},fC=["flowName","stepName","reasoningText","text","name","tool","toolName"],gC=100;function mC(e,t){let n={...pC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return uC}function hC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function yC(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 bC(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 vC(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 xC(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 CC(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function wC(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 AC(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 hc(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");Ir(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=oe(d?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let E=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=o.timestampFormat??"relative";E.textContent=P==="relative"?hC(e.timestamp,n):yC(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=m("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 M=mC(e.type,o.badgeColors),k=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");k.style.backgroundColor=M.bg,k.style.color=M.text,k.style.borderColor=M.text+"50",k.textContent=e.type;let F=o.descriptionFields??fC,z=bC(e.payload,F),w=null;z&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=z);let U=m("div","persona-flex-1 persona-min-w-0"),q=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"),ee=oe("clipboard","12px","currentColor",1.5);return ee&&q.appendChild(ee),q.addEventListener("click",async D=>{D.stopPropagation(),await vC(xC(e)),q.innerHTML="";let $=oe("check","12px","currentColor",1.5);$&&q.appendChild($),setTimeout(()=>{q.innerHTML="";let X=oe("clipboard","12px","currentColor",1.5);X&&q.appendChild(X)},1500)}),f.appendChild(y),f.appendChild(E),W&&f.appendChild(W),f.appendChild(k),w&&f.appendChild(w),f.appendChild(U),f.appendChild(q),b.appendChild(f),d&&b.appendChild(AC(e,a,i)),b}}function Hf(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");Ir(C,y?.panel);let E=[],P="",W="",M=null,k=[],F={},z=0,w=oi(),U=0,q=0,ee=!1,D=null,$=!1,X=0,ye=new Set,be=new Map,He="",re="",me=null,Z,ce,Q,pe,ve=null,he=null,Ae=null;function at(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=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(Ir(j,y?.headerBar),a){he=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",ve=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"),ve.textContent="-- tok/s",Ae=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"),Ae.style.display="none",Ae.style.pointerEvents="none";let Fe=he,Bt=Ae,Ni=()=>{if(!Bt.textContent)return;let Gs=Fe.getBoundingClientRect(),Js=B.getBoundingClientRect();Bt.style.left=`${Gs.left-Js.left}px`,Bt.style.top=`${Gs.bottom-Js.top+4}px`,Bt.style.display="block"},So=()=>{Bt.style.display="none"};he.addEventListener("mouseenter",Ni),he.addEventListener("mouseleave",So),he.appendChild(ve)}let Y=m("div","persona-flex-1");Z=m("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ke=m("option","");Ke.value="",Ke.textContent="All events (0)",Z.appendChild(Ke),ce=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ce.type="button",ce.title="Copy All";let Xe=oe("clipboard-copy","12px","currentColor",1.5);Xe&&ce.appendChild(Xe);let ot=m("span","persona-event-copy-all persona-text-xs");ot.textContent="Copy All",ce.appendChild(ot),he&&j.appendChild(he),j.appendChild(Y),j.appendChild(Z),j.appendChild(ce);let V=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ir(V,y?.searchBar);let je=oe("search","14px","var(--persona-muted, #9ca3af)",1.5),xe=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");je&&xe.appendChild(je),Q=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"),Ir(Q,y?.searchInput),Q.type="text",Q.placeholder="Search event payloads...",pe=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"),pe.type="button",pe.style.display="none";let Ue=oe("x","12px","currentColor",2);return Ue&&pe.appendChild(Ue),V.appendChild(xe),V.appendChild(Q),V.appendChild(pe),B.appendChild(j),B.appendChild(V),Ae&&B.appendChild(Ae),B}let Me,Be=s.find(B=>B.renderEventStreamToolbar);Be?.renderEventStreamToolbar&&r?Me=Be.renderEventStreamToolbar({config:r,defaultRenderer:()=>at(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{P=j,Ze(),ae()},onSearchChange:j=>{W=j,Ze(),ae()}})??at():Me=at();let Oe=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");Oe.style.display="none";function ze(){if(!a||!ve||!he)return;let B=a(),j=CC(B);ve.textContent=j;let Y=wC(B);Ae&&(Ae.textContent=Y,Y||(Ae.style.display="none")),he.setAttribute("aria-label",Y?`Throughput: ${j}, ${Y}`:`Throughput: ${j}`)}let Te=m("div","persona-flex-1 persona-min-h-0 persona-relative"),le=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");le.style.height="100%";let Pe=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");Ir(Pe,y?.scrollIndicator),Pe.style.display="none",Pe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let rt=oe(p,"14px","currentColor",2);rt&&Pe.appendChild(rt);let vt=m("span","");vt.textContent=c,Pe.appendChild(vt);let kt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");kt.style.display="none",Te.appendChild(le),Te.appendChild(kt),Te.appendChild(Pe),C.setAttribute("tabindex","0"),C.appendChild(Me),C.appendChild(Oe),C.appendChild(Te);function St(){let B=t.getAll(),j={};for(let V of B)j[V.type]=(j[V.type]||0)+1;let Y=Object.keys(j).sort(),Ke=Y.length!==k.length||!Y.every((V,je)=>V===k[je]),Ie=!Ke&&Y.some(V=>j[V]!==F[V]),Xe=B.length!==Object.values(F).reduce((V,je)=>V+je,0);if(!Ke&&!Ie&&!Xe||(k=Y,F=j,!Z))return;let ot=Z.value;if(Z.options[0].textContent=`All events (${B.length})`,Ke){for(;Z.options.length>1;)Z.remove(1);for(let V of Y){let je=m("option","");je.value=V,je.textContent=`${V} (${j[V]||0})`,Z.appendChild(je)}ot&&Y.includes(ot)?Z.value=ot:ot&&(Z.value="",P="")}else for(let V=1;V<Z.options.length;V++){let je=Z.options[V];je.textContent=`${je.value} (${j[je.value]||0})`}}function De(){let B=t.getAll();if(P&&(B=B.filter(j=>j.type===P)),W){let j=W.toLowerCase();B=B.filter(Y=>Y.type.toLowerCase().includes(j)||Y.payload.toLowerCase().includes(j))}return B}function de(){return P!==""||W!==""}function Ze(){z=0,U=0,w.resume(),Pe.style.display="none"}function Re(B){ye.has(B)?ye.delete(B):ye.add(B),me=B;let j=le.scrollTop,Y=w.isFollowing();$=!0,w.pause(),ae(),le.scrollTop=j,Y&&w.resume(),$=!1}function fe(){return vo(le,50)}function ae(){q=Date.now(),ee=!1,ze(),St();let B=t.getEvictedCount();B>0?(Oe.textContent=`${B.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",E=De();let j=E.length,Y=t.getSize()>0;j===0&&Y&&de()?(kt.textContent=W?`No events matching '${W}'`:"No events matching filter",kt.style.display="",le.style.display="none"):(kt.style.display="none",le.style.display=""),ce&&(ce.title=de()?`Copy Filtered (${j})`:"Copy All"),d&&!w.isFollowing()&&j>z&&(U+=j-z,vt.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Pe.style.display=""),z=j;let Ke=t.getAll(),Ie=Ke.length>0?Ke[0].timestamp:0,Xe=new Set(E.map(je=>je.id));for(let je of ye)Xe.has(je)||ye.delete(je);let ot=P!==He||W!==re,V=be.size===0&&E.length>0;if(ot||V||E.length===0){le.innerHTML="",be.clear();let je=document.createDocumentFragment();for(let xe=0;xe<E.length;xe++){let Ue=hc(E[xe],xe,Ie,u,ye,Re,s,r);be.set(E[xe].id,Ue),je.appendChild(Ue)}le.appendChild(je),He=P,re=W,me=null}else{if(me!==null){let xe=be.get(me);if(xe&&xe.parentNode===le){let Ue=E.findIndex(Fe=>Fe.id===me);if(Ue>=0){let Fe=hc(E[Ue],Ue,Ie,u,ye,Re,s,r);le.insertBefore(Fe,xe),xe.remove(),be.set(me,Fe)}}me=null}let je=new Set(E.map(xe=>xe.id));for(let[xe,Ue]of be)je.has(xe)||(Ue.remove(),be.delete(xe));for(let xe=0;xe<E.length;xe++){let Ue=E[xe];if(!be.has(Ue.id)){let Fe=hc(Ue,xe,Ie,u,ye,Re,s,r);be.set(Ue.id,Fe),le.appendChild(Fe)}}}w.isFollowing()&&(le.scrollTop=le.scrollHeight)}function Le(){if(Date.now()-q>=gC){D!==null&&(cancelAnimationFrame(D),D=null),ae();return}ee||(ee=!0,D=requestAnimationFrame(()=>{D=null,ae()}))}let it=(B,j)=>{if(!ce)return;ce.innerHTML="";let Y=oe(B,"12px","currentColor",1.5);Y&&ce.appendChild(Y);let Ke=m("span","persona-text-xs");Ke.textContent="Copy All",ce.appendChild(Ke),setTimeout(()=>{ce.innerHTML="";let Ie=oe("clipboard-copy","12px","currentColor",1.5);Ie&&ce.appendChild(Ie);let Xe=m("span","persona-text-xs");Xe.textContent="Copy All",ce.appendChild(Xe),ce.disabled=!1},j)},ue=async()=>{if(ce){ce.disabled=!0;try{let B;de()?B=E:n?(B=await n(),B.length===0&&(B=t.getAll())):B=t.getAll();let j=B.map(Y=>{try{return JSON.parse(Y.payload)}catch{return Y.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),it("check",1500)}catch{it("x",1500)}}},we=()=>{Z&&(P=Z.value,Ze(),ae())},te=()=>{!Q||!pe||(pe.style.display=Q.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{W=Q.value,Ze(),ae()},150))},S=()=>{!Q||!pe||(Q.value="",W="",pe.style.display="none",M&&clearTimeout(M),Ze(),ae())},O=()=>{if($)return;let B=le.scrollTop,{action:j,nextLastScrollTop:Y}=ri({following:w.isFollowing(),currentScrollTop:B,lastScrollTop:X,nearBottom:fe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});X=Y,j==="resume"?(w.resume(),U=0,Pe.style.display="none"):j==="pause"&&(w.pause(),d&&(vt.textContent=c,Pe.style.display=""))},v=B=>{let j=si({following:w.isFollowing(),deltaY:B.deltaY,nearBottom:fe(),resumeWhenNearBottom:!0});j==="pause"?(w.pause(),d&&(vt.textContent=c,Pe.style.display="")):j==="resume"&&(w.resume(),U=0,Pe.style.display="none")},R=()=>{d&&(le.scrollTop=le.scrollHeight,w.resume(),U=0,Pe.style.display="none")},T=B=>{let j=B.target;if(!j||j.closest("button"))return;let Y=j.closest("[data-event-id]");if(!Y)return;let Ke=Y.getAttribute("data-event-id");Ke&&Re(Ke)},I=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Q?.focus(),Q?.select();return}B.key==="Escape"&&(Q&&document.activeElement===Q?(S(),Q.blur(),C.focus()):o&&o())};ce&&ce.addEventListener("click",ue),Z&&Z.addEventListener("change",we),Q&&Q.addEventListener("input",te),pe&&pe.addEventListener("click",S),le.addEventListener("scroll",O),le.addEventListener("wheel",v,{passive:!0}),le.addEventListener("click",T),Pe.addEventListener("click",R),C.addEventListener("keydown",I);function K(){M&&clearTimeout(M),D!==null&&(cancelAnimationFrame(D),D=null),ee=!1,be.clear(),ce&&ce.removeEventListener("click",ue),Z&&Z.removeEventListener("change",we),Q&&Q.removeEventListener("input",te),pe&&pe.removeEventListener("click",S),le.removeEventListener("scroll",O),le.removeEventListener("wheel",v),le.removeEventListener("click",T),Pe.removeEventListener("click",R),C.removeEventListener("keydown",I)}return{element:C,update:Le,destroy:K}}}function yc(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 Bf(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=te=>({start:te===!1?!1:typeof te=="object"&&te?te.start!==!1:!0,end:te===!1?!1:typeof te=="object"&&te?te.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"),$?.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 E=m("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=s;let P=pt({icon:"x",label:a});P.addEventListener("click",()=>{f(),t.onDismiss?.()});let W="rendered",M=yo({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:te=>{W=te==="source"?"source":"rendered",it()}}),k=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),F=n?.documentToolbarShowCopyLabel===!0,z=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,U=!!(z&&w&&w.length>0),q=null,ee,D=null,$=null;if(r&&(F||z)&&!U){if(ee=F?ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),z){let te=oe("chevron-down",14,"currentColor",2);te&&ee.appendChild(te)}}else r&&U?(q=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ee=F?ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=pt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(ee,D)):r?ee=pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(ee=pt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&ee.classList.add("persona-hidden"));let X=r?pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):pt({icon:"refresh-cw",label:"Refresh"}),ye=r?pt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):pt({icon:"x",label:a}),be=pt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&be.classList.add("persona-hidden");let He=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),re=e.features?.artifacts?.toolbarActions??[],me=()=>{let te=Te.find(R=>R.id===le)??Te[Te.length-1],S=te?.id??null,O=te?.artifactType==="markdown"?te.markdown??"":"",v=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:O,jsonPayload:v,id:S}},Z=async()=>{let te=Te.find(S=>S.id===le)??Te[Te.length-1];try{await navigator.clipboard.writeText(Is(te))}catch{}};if(ee.addEventListener("click",async()=>{let te=n?.onDocumentToolbarCopyMenuSelect;if(te&&U){let{markdown:S,jsonPayload:O,id:v}=me();try{await te({actionId:"primary",artifactId:v,markdown:S,jsonPayload:O})}catch{}return}await Z()}),D&&w?.length){let te=()=>y.closest("[data-persona-root]")??document.body,S=()=>{$=Xo({items:w.map(O=>({id:O.id,label:O.label})),onSelect:async O=>{let{markdown:v,jsonPayload:R,id:T}=me(),I=n?.onDocumentToolbarCopyMenuSelect;try{I?await I({actionId:O,artifactId:T,markdown:v,jsonPayload:R}):O==="markdown"||O==="md"?await navigator.clipboard.writeText(v):O==="json"||O==="source"?await navigator.clipboard.writeText(R):await navigator.clipboard.writeText(v||R)}catch{}},anchor:q??D,position:"bottom-right",portal:te()})};y.isConnected?S():requestAnimationFrame(S),D.addEventListener("click",O=>{O.stopPropagation(),$?.toggle()})}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),ye.addEventListener("click",()=>{f(),t.onDismiss?.()});let ce=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),q?k.append(q,X,ye):k.append(ee,X,ye),k.insertBefore(He,ye),k.insertBefore(be,ye),C.append(M.element,ce,k);else{let te=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");te.append(ee,He,be,P),C.appendChild(E),C.appendChild(te)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Q=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&&Q.style.setProperty("--persona-artifact-tab-fade-size",d);let pe=e.features?.artifacts?.renderTabBar,ve=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=yc(Q,{onSelect:te=>t.onSelect(Te[te].id)}),Ae=te=>{let S=te.scrollWidth-te.clientWidth,O=S>1,v=Math.abs(te.scrollLeft);te.classList.toggle("persona-artifact-tab-fade-start",c&&O&&v>1),te.classList.toggle("persona-artifact-tab-fade-end",u&&O&&v<S-1)},at=0,Me=()=>{if(at)return;let te=()=>{at=0,Ae(Q)};at=typeof requestAnimationFrame=="function"?requestAnimationFrame(te):setTimeout(te,0)};Q.addEventListener("scroll",()=>Me(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ae(Q)).observe(Q);let Be=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Oe=()=>{Be.scrollLeft=0},ze=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Oe):setTimeout(Oe,0)};if(i){for(let te of[Q,ve])te.style.paddingLeft=i,te.style.paddingRight=i;Be.style.padding=i}y.appendChild(C),y.appendChild(Q),y.appendChild(ve),y.appendChild(Be);let Te=[],le=null,Pe=!1,rt=!1,vt=!0,kt=!1,St=null,De="",de=null,Ze=!1,Re=te=>te.artifactType==="markdown"&&!!te.file||r?W:"rendered",fe=te=>{r||(te&&!Ze?(C.insertBefore(M.element,E),Ze=!0):!te&&Ze&&(M.element.remove(),Ze=!1))},ae=()=>le&&Te.find(te=>te.id===le)||Te[Te.length-1],Le=()=>{let te=Ls(ae());if(!te){He.replaceChildren();return}let S=re.filter(O=>O.visible===void 0||O.visible(te)).map(O=>Mr(O,{documentChrome:r,onClick:()=>{let v=Ls(ae());if(v)try{Promise.resolve(O.onClick(v)).catch(()=>{})}catch{}}}));He.replaceChildren(...S)},it=()=>{Le();let te=r&&Te.length<=1,S=!!pe;if(Q.classList.toggle("persona-hidden",te||S),ve.classList.toggle("persona-hidden",te||!S),S&&pe){let R=Te.map(T=>T.id).join("|")+" "+(le??"");if(R!==De){De=R;let T=pe({records:Te,selectedId:le,onSelect:t.onSelect});ve.firstElementChild!==T&&ve.replaceChildren(T)}}else{he.beforeRender(),Q.replaceChildren();let R=[],T=-1;for(let[I,K]of Te.entries()){let B=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");B.type="button";let j=K.artifactType==="markdown"?K.file:void 0,Y=j?Pn(j.path):K.title||K.id.slice(0,8),Ke=j?.path||K.title||Y;B.textContent=Y,B.title=Ke,B.setAttribute("aria-label",Ke),K.id===le&&(B.classList.add("persona-bg-persona-container","persona-border-persona-border"),T=I),B.addEventListener("click",()=>t.onSelect(K.id)),Q.appendChild(B),R.push(B)}if(he.render(R,T),T>=0&&le!==St){St=le;let I=R[T];typeof I.scrollIntoView=="function"&&I.scrollIntoView({block:"nearest",inline:"nearest"})}Ae(Q)}let O=le&&Te.find(R=>R.id===le)||Te[Te.length-1];if(!O){Be.replaceChildren(),de=null,fe(!1);return}let v=O.artifactType==="markdown"?O.file:void 0;if(fe(!!v),r){let R=v?go(v):O.artifactType==="markdown"?"MD":O.component??"Component",T=(O.title||"Document").trim(),I=v?Pn(v.path):T.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${I} \xB7 ${R}`}else E.textContent=v?Pn(v.path):s;de?(de.el.parentElement!==Be&&Be.replaceChildren(de.el),de.update(O)):(de=ti(O,{config:e,resolveViewMode:Re}),Be.replaceChildren(de.el)),Be.classList.toggle("persona-artifact-content-flush",!!Be.querySelector(".persona-code-pre"))},ue=()=>{let te=Te.length>0;if(y.classList.toggle("persona-hidden",!te),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;te&&v&&Pe?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},we=()=>{kt=!1,it(),ue()};return{element:y,backdrop:b,update(te){let S=te.selectedId??te.artifacts[te.artifacts.length-1]?.id??null,O=S!==le;Te=te.artifacts,le=S,Te.length>0&&(Pe=!0),kt=!0,vt&&we(),O&&Oe()},setMobileOpen(te){Pe=te,!te&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(te){te!==rt&&(rt=te,ze());let S=oe(te?"minimize":"maximize",16,"currentColor",2);S&&be.replaceChildren(S);let O=te?"Collapse artifacts panel":"Expand artifacts panel";be.setAttribute("aria-label",O),be.title=O},setExpandToggleVisible(te){be.classList.toggle("persona-hidden",!te)},setCopyButtonVisible(te){r||ee.classList.toggle("persona-hidden",!te)},setCustomActions(te){re=te,Le()},setTabFade(te){let S=p(te);S.start===c&&S.end===u||(c=S.start,u=S.end,Ae(Q))},setRenderTabBar(te){te!==pe&&(pe=te,De="",it())},setVisible(te){te!==vt&&(vt=te,te&&kt&&we())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function Df(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function SC(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 Of=["panel","seamless","detached"];function bc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Of.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function vc(e){return!e||!Xt(e)?!1:bc(e)==="detached"}function qs(e,t){if(!Xt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),SC(e),Df(e,t);return}let n=t.features?.artifacts?.layout,o=bc(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"),Df(e,t)}function Vs(e,t){for(let i of Of)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=bc(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 Nf(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var TC=new Set(["__proto__","prototype","constructor"]),MC=new Set(["collapsed","card","panel","inline"]),Ff=new Set(["markdown","component"]),EC=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,er=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wi=e=>!TC.has(e),xc=e=>typeof e=="string"&&MC.has(e),tr=e=>Object.keys(e).length>0;function In(e,t,n,o){e.push({path:t,code:n,message:o})}var kC="Ignored because this key is not part of the persisted preference schema.",Ci="Ignored an unsupported value.",PC="Expected collapsed, panel, or inline.",LC='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',_f={kind:"mode",message:Ci},Wr={kind:"string",message:"Expected a CSS length string."},Vn={kind:"boolean"},RC={paneWidth:Wr,paneMaxWidth:Wr,paneMinWidth:Wr,expandedPanelWidth:Wr,resizableMinWidth:Wr,resizableMaxWidth:Wr,expandLauncherPanelWhenOpen:Vn,resizable:Vn},IC={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Vn,showReasoning:Vn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ci},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ci},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ci},expandable:Vn,grouped:Vn}},reasoningDisplay:{kind:"object",children:{expandable:Vn,activePreview:Vn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:_f,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:_f,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Ff,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Ff}}},filePreview:{kind:"object",children:{enabled:Vn}},layout:{kind:"object",children:RC}}}}};function $f(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:In(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:In(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:In(o,n,"invalid_value",t.message);case"mode":return xc(e)?rn(e):In(o,n,"invalid_value",t.message);case"modeMap":{if(!er(e))return In(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:_o(a);wi(a)&&(r?r.has(a):EC.test(d))?xc(i)?s[d]=rn(i):In(o,`${n}.${a}`,"invalid_value",PC):In(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LC)}return tr(s)?s:void 0}case"object":{if(t.bareMode&&xc(e))return rn(e);if(!er(e))return In(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))(!wi(i)||!r.includes(i))&&In(o,s(i),"unknown_key",kC);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&&In(o,s(i),"deprecated_key",d.deprecated),p===void 0)continue;let c=d.alias??i,u=a[c];a[c]=er(u)&&er(p)?{...u,...p}:p}return tr(a)?a:void 0}}}function jf(e){let t=[];return{preferences:(e===null?void 0:$f(e,IC,"",t))??{},issues:t}}function Hr(e){if(Array.isArray(e))return e.map(Hr);if(!er(e))return e;let t={};for(let[n,o]of Object.entries(e))wi(n)&&o!==void 0&&(t[n]=Hr(o));return t}function Uf(e,t){let n=Hr(e);for(let[o,r]of Object.entries(t)){if(!wi(o)||r===void 0)continue;let s=n[o];n[o]=er(s)&&er(r)?Uf(s,r):Hr(r)}return n}function WC(e){let t={},n;for(let r of e){let s=jf(r).preferences;n=zf(n,s.artifacts?.display),t=Uf(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function HC(e,t){if(t===void 0)return e===void 0?void 0:Hr(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}:{},...tr(r)?{byMediaType:r}:{}};return tr(s)?s:void 0}function zf(e,t){if(t===void 0)return e===void 0?void 0:Hr(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=HC(n.files,t.files),a={...o?{default:o}:{},...tr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return tr(a)?a:void 0}function qf(e={},t){let n=WC(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=zf(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 Ai(e){let t=e.preferences;return!t||!tr(t)?e:{...e,features:qf(e.features??{},[t])}}function BC(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 DC(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 OC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function NC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Cc(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 Vf(e,t,n,o,r,s){let a=BC(r,200),i=NC(t,n,o,200);i=Math.max(a,i);let d=DC(s);return d!==null&&(i=Math.min(i,d)),OC(e,a,i)}var Kf={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},wc=(e,t,n,o)=>{let 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=Kf[a]??Kf.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 E=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=y.label,C.appendChild(E);let P=y.type??"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),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}-${y.name}`,W.name=y.name,W.placeholder=y.placeholder??"",y.required&&(W.required=!0),C.appendChild(W),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",E=new FormData(c),P={};E.forEach((W,M)=>{P[M]=W}),P.type=a,f.disabled=!0,b.textContent="Submitting\u2026";try{let W=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let M=await W.json();b.textContent=M.message??"Thanks! We'll be in touch soon.",M.success&&M.nextPrompt&&await o.sendMessage(String(M.nextPrompt))}catch(W){b.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ac=class{constructor(){this.plugins=new Map}register(t){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()}},Si=new Ac;var Gf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),FC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Jf=(e,t,n)=>{if(!Gf(e)||!Gf(t)||FC.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]=Jf(e[r],t[r],s)}return o};function Ti(e,t){let n=Jf(e,t,"");return Es(n)}var Xf=()=>{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 _C=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},$C=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},Mi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=_C(e),n=$C(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}},Sc=e=>typeof e=="string"?e:e==null?"":String(e),Br={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Sc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Sc(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:Sc(n.text)}}},Yf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ei=e=>{let t=new Set(Yf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Yf(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 jC=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}},UC=e=>e.map(t=>({...t,streaming:!1})),zC=e=>e.map(t=>({...t,status:"complete"})),Tc=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?jC(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?UC(n.messages):void 0,artifacts:n.artifacts?zC(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)}}}};import{parse as qC,STR as VC,OBJ as KC}from"partial-json";function GC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function JC(e,t){if(!GC(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 Mc(){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=qC(n,VC|KC),s=JC(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function XC(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ec(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Ln.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 YC(){let e=Mc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Qf(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 ki(e){let t=Qf(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 kc(e){let t=Qf(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 QC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Pc(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=QC}=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 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 P=[];for(let z=1;z<=5;z++){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",`${z} star${z>1?"s":""}: ${p[z-1]}`),w.title=p[z-1],w.dataset.rating=String(z),w.innerHTML=`
|
|
41
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Mt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let T=a.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let T=a.subtitle??"Here to help you get answers fast";d.textContent=T,d.setAttribute("title",T)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let T=a.agentIconSize??"40px";if(g.style.height=T,g.style.width=T,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let L=parseFloat(T)||24,H=se(a.agentIconName,L*.6,"var(--persona-text-inverse, #ffffff)",2);H?(g.appendChild(H),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let T=a.agentIconSize??"40px";b.style.height=T,b.style.width=T,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 T=a.callToActionIconSize??"32px";f.style.height=T,f.style.width=T,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 L=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,L=(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 H=parseFloat(T)||24,O=Math.max(H-L,8),_=se(a.callToActionIconName,O,"currentColor",2);_?f.appendChild(_):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let x=a.position&&dn[a.position]?dn[a.position]:dn["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",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?S:`${C} ${x}`,i||(n.style.zIndex=String(a.zIndex??_t));let M="1px solid var(--persona-border, #e5e7eb)",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??M,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:P,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=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}},zw="teaser-dismissed",qf=new Set,zf=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${zw}`},qw=(e,t)=>{if(qf.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Vw=(e,t)=>{if(qf.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},Kw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Gw=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Mt(e??{})?null:t},Vf=(e,t)=>{let n=y("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,i=null,p=null,d=!1,c=!1,g=!1,b=!1,f=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,x=()=>{p!==null&&(clearTimeout(p),p=null)},C=()=>{!s||!d||(d=!1,s.hidden=!0)},S=J=>{x(),g=!0,C(),Vw(zf(o),J&&f())},M=J=>{!r||g||S(J==="user"&&d)},P=()=>{p=null,!(!s||g||b)&&(c=!0,d=!0,s.hidden=!1,!(Kw()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},T=()=>{!r||!s||g||c||b||qw(zf(o),f())||(x(),p=setTimeout(P,Math.max(0,r.delayMs??0)))},L=()=>{S(f()),t()},H=J=>{J.stopPropagation(),S(f())},_=rd(e,()=>{M("user"),t()}),U=()=>{x(),i?.removeEventListener("click",L),a?.removeEventListener("click",H),s?.remove(),s=null,i=null,a=null,d=!1},z=()=>{i=Me("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",L),a=Me("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",H),s=Me("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},i,a),n.insertBefore(s,_.element)},Y=()=>{let J=o.launcher?.position??"bottom-right",me=dn[J]??dn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",_.element.style.position="";return}n.className=In("persona-launcher-surface",me),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??_t),_.element.style.position="static"},A=J=>{let me=Gw(J);if(r=me,!me){U();return}s||z(),i.textContent=me.text,a.hidden=me.dismissible===!1,a.setAttribute("aria-label",me.dismissLabel??"Dismiss message"),T()},G=J=>{o=J,_.update(J),A(J),Y()},Q=(J,me="user")=>{b=J,J&&M(me)},le=()=>{U(),_.destroy(),n.remove()};return n.appendChild(_.element),e&&(A(e),Y()),{element:n,launcher:_,get teaser(){return s?{element:s,show:P,dismiss:S}:null},setPanelOpen:Q,update:G,destroy:le}};var Kf=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=$f(e),s=Uf(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,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:p,composer:d,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{d.footer.replaceWith(b),d.footer=b}}},sd=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>rd(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Vf(e,n);return{instance:r,element:r.element}};var Jw=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},Yw=(e,t,n)=>`${Jw(e)}plugin:${t}:${n}`,Gf=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>Yw(e(),r,a);return{get:a=>{let i=s(a),p=o();if(p)try{return p.getItem(i)}catch{n=!0}return t.get(i)??null},set:(a,i)=>{let p=s(a),d=o();if(d)try{d.setItem(p,i);return}catch{n=!0}t.set(p,i)},remove:a=>{let i=s(a);t.delete(i);let p=o();if(p)try{p.removeItem(i)}catch{n=!0}}}}};var os=new Set,Xw=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Qw=(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
|
+
`):""},Jf=(e,t)=>{let n=os.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=se(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ad=(e,t)=>{let n=e.reasoning,o=y("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&&os.has(e.id),i=n.status!=="complete",p=Qw(e,r.previewMaxLines??3),d=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",f=t?.reasoning??{},x=String(n.startedAt??Date.now()),C=()=>{let le=y("span","");return le.setAttribute("data-tool-elapsed",x),le.textContent=ai(n),le},S=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:b,previewText:p,isActive:i,config:t??{},elapsed:ai(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(g.textContent=S,c.appendChild(g)):S instanceof HTMLElement?c.appendChild(S):(g.textContent=b,c.appendChild(g));let M=y("span","persona-text-xs persona-text-persona-primary");M.textContent=dg(n),c.appendChild(M);let P=r.loadingAnimation??"none",T=f.activeTextTemplate,L=f.completeTextTemplate,H=i?T:L,O=S instanceof HTMLElement,_=(le,J)=>{g.textContent="";let me=ii(le,""),ee=0;for(let ye of me){let Z=ye.styles.length>0?(()=>{let ue=y("span",ye.styles.map(te=>`persona-tool-text-${te}`).join(" "));return g.appendChild(ue),ue})():g;if(ye.isDuration&&i)Z.appendChild(C());else{let ue=ye.isDuration?ai(n):ye.text;J?ee=ko(Z,ue,ee):Z.appendChild(document.createTextNode(ue))}}};if(!O&&H)if(M.style.display="none",g.style.display="",i&&P!=="none"){let le=f.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),P==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${le}ms`),_(H,!1)):(g.classList.add(`persona-tool-loading-${P}`),g.style.setProperty("--persona-tool-anim-duration",`${le}ms`),P==="shimmer-color"&&(f.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),_(H,!0))}else _(H,!1);else if(!O&&i&&P!=="none"){g.style.display="";let le=f.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),P==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${le}ms`);else{g.classList.add(`persona-tool-loading-${P}`),g.style.setProperty("--persona-tool-anim-duration",`${le}ms`),P==="shimmer-color"&&(f.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let J=g.textContent||b;g.textContent="",ko(g,J,0)}n.status==="complete"&&(g.style.display="none")}else O||(n.status==="complete"?g.style.display="none":g.style.display="");let U=null;if(s){U=y("div","persona-flex persona-items-center");let J=se(a?"chevron-up":"chevron-down",16,"currentColor",2);J?U.appendChild(J):U.textContent=a?"Hide":"Show";let me=y("div","persona-flex persona-items-center persona-ml-auto");me.append(U),d.append(c,me)}else d.append(c);let z=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","reasoning"),z.style.display="none",z.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&p){let le=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});Xw(z,le)||(z.textContent=p),z.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,z),o;let Y=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Y.style.display=a?"":"none";let A=n.chunks.join(""),G=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=A||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Y.appendChild(G),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let J=se(a?"chevron-up":"chevron-down",16,"currentColor",2);J?U.appendChild(J):U.textContent=a?"Hide":"Show"}Y.style.display=a?"":"none",z.style.display=a?"none":z.textContent||z.childNodes.length?"":"none"})(),o.append(d,z,Y),o};var rs=new Set,Zw=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),eA=(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=So(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
44
|
+
`):""},id=(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)"},tA=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=eA(e,o?.previewMaxLines??3),a=n?pg(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),i&&p.activeTextTemplate?d=hc(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=hc(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},Yf=(e,t,n)=>{let o=rs.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=se(o?"chevron-up":"chevron-down",16,c,2);g?d.appendChild(g):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},ld=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=y("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&&rs.has(e.id),{summary:p,previewText:d,isActive:c}=tA(e,t),g=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let b=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let x=String(n.startedAt??Date.now()),C=()=>{let A=y("span","");return A.setAttribute("data-tool-elapsed",x),A.textContent=Vs(n),A},S=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Vs(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(f.textContent=S,b.appendChild(f)):S instanceof HTMLElement?b.appendChild(S):(f.textContent=p,b.appendChild(f));let M=s.loadingAnimation??"none",P=o.activeTextTemplate,T=o.completeTextTemplate,L=c?P:T,H=S instanceof HTMLElement,O=(A,G)=>{f.textContent="";let Q=n.name?.trim()||"tool",le=ii(A,Q),J=0;for(let me of le){let ee=me.styles.length>0?(()=>{let ye=y("span",me.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(ye),ye})():f;if(me.isDuration&&c)ee.appendChild(C());else{let ye=me.isDuration?Vs(n):me.text;G?J=ko(ee,ye,J):ee.appendChild(document.createTextNode(ye))}}};if(!H)if(c&&M!=="none"){let A=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),M==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${A}ms`),L&&O(L,!1);else if(f.classList.add(`persona-tool-loading-${M}`),f.style.setProperty("--persona-tool-anim-duration",`${A}ms`),M==="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)),L)O(L,!0);else{let G=f.textContent||p;f.textContent="",ko(f,G,0)}}else L&&O(L,!1);let _=null;if(a){_=y("div","persona-flex persona-items-center");let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=se(i?"chevron-up":"chevron-down",16,A,2);G?_.appendChild(G):_.textContent=i?"Hide":"Show";let Q=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(_),g.append(b,Q)}else g.append(b);let U=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let A=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Zw(U,A)||(U.textContent=d),U.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(g,U),r;let z=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(z.style.display=i?"":"none",o.contentBackgroundColor&&(z.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(z.style.color=o.contentTextColor),o.contentPaddingX&&(z.style.paddingLeft=o.contentPaddingX,z.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(z.style.paddingTop=o.contentPaddingY,z.style.paddingBottom=o.contentPaddingY),n.name){let A=y("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?A.style.color=o.contentTextColor:o.headerTextColor&&(A.style.color=o.headerTextColor),A.textContent=n.name,z.appendChild(A)}if(n.args!==void 0){let A=y("div","persona-space-y-1"),G=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",id(Q,o),Q.textContent=So(n.args),A.append(G,Q),z.appendChild(A)}if(n.chunks&&n.chunks.length){let A=y("div","persona-space-y-1"),G=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",id(Q,o),Q.textContent=n.chunks.join(""),A.append(G,Q),z.appendChild(A)}if(n.status==="complete"&&n.result!==void 0){let A=y("div","persona-space-y-1"),G=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",id(Q,o),Q.textContent=So(n.result),A.append(G,Q),z.appendChild(A)}if(n.status==="complete"&&typeof n.duration=="number"){let A=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(A.style.color=o.contentTextColor),A.textContent=`Duration: ${n.duration}ms`,z.appendChild(A)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),_){_.innerHTML="";let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=se(i?"chevron-up":"chevron-down",16,A,2);G?_.appendChild(G):_.textContent=i?"Hide":"Show"}z.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(g,U,z),r};var yr=new Map,Vi=e=>{let n=(e.startsWith(Dn)?e.slice(Dn.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)},Xf=e=>e?.approval!==!1?e?.approval:void 0,Qf=(e,t)=>{let n=Xf(t)?.detailsDisplay??"collapsed";return yr.get(e)??n==="expanded"},Zf=(e,t,n)=>{let o=Xf(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=se(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},em=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Qf(e,n);Zf(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=y("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=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=se(p,20,d,2);c&&i.appendChild(c);let g=y("div","persona-flex-1 persona-min-w-0"),b=y("div","persona-flex persona-items-center persona-gap-2"),f=y("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 _=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",n.status),n.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):n.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):n.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),b.appendChild(_)}g.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(Dn)?Fs(n.toolName):void 0,S=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),M=!n.toolName,P=S||(M?n.description:`The assistant wants to use \u201C${C??Vi(n.toolName)}\u201D.`),T=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=P,g.appendChild(T),n.reason){let _=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");_.setAttribute("data-approval-reason","true"),o?.reasonColor?_.style.color=o.reasonColor:o?.descriptionColor&&(_.style.color=o.descriptionColor);let U=y("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,_.appendChild(U),_.appendChild(document.createTextNode(n.reason)),g.appendChild(_)}let L=o?.detailsDisplay??"collapsed",H=!!n.description&&!M,O=H||!!n.parameters;if(L!=="hidden"&&O){let _=Qf(e.id,t),U=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let z=y("span");z.setAttribute("data-approval-details-label","true");let Y=y("span","persona-inline-flex persona-items-center");Y.setAttribute("data-approval-details-chevron","true"),U.append(z,Y),Zf(U,_,t),g.appendChild(U);let A=y("div");if(A.setAttribute("data-approval-details","true"),A.style.display=_?"":"none",H){let G=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,A.appendChild(G)}if(n.parameters){let G=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=So(n.parameters),A.appendChild(G)}g.appendChild(A)}if(r){let _=y("div","persona-flex persona-gap-2 persona-mt-2");_.setAttribute("data-approval-buttons","true");let U=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let z=se("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);z&&(z.style.marginRight="4px",U.appendChild(z));let Y=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(Y);let A=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");A.type="button",A.style.backgroundColor=o?.denyButtonColor??"transparent",A.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",A.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,A.setAttribute("data-approval-action","deny");let G=se("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",A.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");A.appendChild(Q),_.append(U,A),g.appendChild(_)}return a.append(i,g),s.appendChild(a),s};function nA(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function tm(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,g=e.container??nA(t),b=!1,f=null,x=()=>{if(!b)return;let M=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${M.width}px`),a&&(n.style.maxWidth=`${M.width}px`);let P=n.getBoundingClientRect(),T=i?.()??null,L=T!=null?M.top+T:M.top,H=o==="top-start"||o==="top-end"?L-r-P.height:M.bottom+r,_=o==="bottom-end"||o==="top-end"?M.right-P.width:M.left,U=a?.()??null;if(U!=null){let z=Math.max(M.left,M.right-P.width);_=Math.min(Math.max(M.left+U,M.left),z)}n.style.top=`${H}px`,n.style.left=`${_}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},S=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),g.appendChild(n),x();let M=(t.ownerDocument??document).defaultView??window,P=t.ownerDocument??document,T=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}x()},L=O=>{let _=typeof O.composedPath=="function"?O.composedPath():[];_.includes(n)||_.includes(t)||(C(),c?.("outside"))},H=M.setTimeout(()=>{P.addEventListener("pointerdown",L,!0)},0);M.addEventListener("scroll",T,!0),M.addEventListener("resize",T),f=()=>{M.clearTimeout(H),P.removeEventListener("pointerdown",L,!0),M.removeEventListener("scroll",T,!0),M.removeEventListener("resize",T)},d?.()};return{get isOpen(){return b},open:S,close:C,toggle:()=>b?C():S(),reposition:x,destroy:C}}function nm(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var oA=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),om=(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))},br=(e,t)=>{om(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)},rA=e=>e?.approval!==!1?e?.approval:void 0,sA=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return yr.get(e)??n==="expanded"},cd=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},aA=(e,t)=>{let n=y("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Dn)?Fs(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 p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},iA=e=>{let t=y("div","persona-approval-resolved"),n=se("ban",15,"currentColor",2);n&&t.appendChild(n);let o=y("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},lA=(e,t,n,o,r,s,a)=>{let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",g=d||c,b=g&&sA(t.id,o),f=o?.showDetailsLabel??"Show details",x=o?.hideDetailsLabel??"Hide details",C=y("button","persona-approval-head");C.type="button",g?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?x:f)):C.setAttribute("data-static","true");let S=y("span","persona-approval-logo"),M=se("shield-check",16,"currentColor",2);M&&S.appendChild(M),C.appendChild(S);let P=aA(n,o);if(g){let U=y("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let z=se("chevron-down",14,"currentColor",2);z&&U.appendChild(z),P.append(" "),P.appendChild(U)}C.appendChild(P),i.appendChild(C);let T=y("div","persona-approval-body");if(g){let U=y("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!b,d){let z=y("p","persona-approval-desc");o?.descriptionColor&&(z.style.color=o.descriptionColor),z.textContent=n.description,U.appendChild(z)}if(c){let z=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(z.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(z.style.color=o.parameterTextColor),z.textContent=So(n.parameters),U.appendChild(z)}T.appendChild(U)}if(n.reason){let U=y("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let z=y("span","persona-approval-reason-label");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(z,document.createTextNode(n.reason)),T.appendChild(U)}let L=y("div","persona-approval-actions"),H=null,O=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},_=y("button","persona-approval-deny");if(_.type="button",_.setAttribute("data-action","deny"),o?.denyButtonColor&&(_.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(_.style.color=o.denyButtonTextColor),_.append(o?.denyLabel??"Deny"),a){let U=y("div","persona-approval-split"),z=y("button","persona-approval-primary");z.type="button",z.setAttribute("data-action","always"),O(z),z.append(o?.approveLabel??"Always allow",cd("\u23CE"));let Y=y("button","persona-approval-caret");Y.type="button",Y.setAttribute("data-action","toggle-menu"),Y.setAttribute("aria-label","More options"),O(Y);let A=se("chevron-down",15,"currentColor",2);A&&Y.appendChild(A),U.append(z,Y),L.append(U,_),_.append(cd("Esc"));let G=y("div","persona-approval-menu"),Q=y("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",cd("\u2318\u23CE")),G.appendChild(Q),H=tm({anchor:U,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,H),Q.addEventListener("click",()=>{br(e,t.id),r()})}else{let U=y("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),O(U),U.append(o?.approveLabel??"Allow"),L.append(U,_)}return T.appendChild(L),i.appendChild(T),i.addEventListener("click",U=>{let z=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!z)return;let Y=z.getAttribute("data-action");if(Y==="toggle-params"){let A=i.querySelector('[data-role="params"]');if(A){let G=A.hidden;A.hidden=!G,C.setAttribute("aria-expanded",G?"true":"false"),C.setAttribute("aria-label",G?x:f),yr.set(t.id,G)}return}if(Y==="toggle-menu"){H?.toggle();return}if(Y==="always"){br(e,t.id),r({remember:!0});return}if(Y==="allow"){br(e,t.id),r();return}if(Y==="deny"){br(e,t.id),s();return}}),i},rm=()=>{let e=oA();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let p=rA(a);if(i.status!=="pending"){if(br(e,o.id),i.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return iA(i)}om(e,o.id);let d=p?.enableAlwaysAllow===!0,c=lA(e,o,i,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=b=>{nm(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),br(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])br(e,o);e.latestPendingApprovalId=null}}};var ha=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 ya=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 cA=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),dA=new Set(["step_start","execution_start"]),pA=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),uA=new Set(["step_complete","agent_turn_complete"]),gA=new Set(["flow_complete","agent_complete"]),sm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),im=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,vr=(e,t)=>{let n=e[t];return im(n)?n:void 0};function dd(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 fA(e,t){return typeof t.type=="string"?t.type:e}function mA(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 hA(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 am(e){let t=vr(e,"result"),n=[vr(e,"tokens"),vr(e,"totalTokens"),t?vr(t,"tokens"):void 0,vr(e,"usage"),t?vr(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 yA(e){let t=vr(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 bA(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ba=class{constructor(t=bA){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(!im(n)){sm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=fA(t,n),r=this.now();if(cA.has(o)){this.startRun(r);return}if(dA.has(o)){this.run||this.startRun(r);return}if(pA.has(o)){if(!hA(o,n))return;let s=mA(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+dd(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Gi(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(uA.has(o)){if(!this.run)return;let s=this.run,a=am(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+dd(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Gi(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(gA.has(o)){if(!this.run)return;let s=this.run,a=am(n),i=a??s.exactOutputTokens+dd(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Gi(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(sm.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:yA(n)??o-t.startedAt}};function ss(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var vA={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)"}},xA={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},CA=["flowName","stepName","reasoningText","text","name","tool","toolName"],wA=100;function AA(e,t){let n={...vA,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return xA}function SA(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function TA(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 EA(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 MA(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 kA(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 LA(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function PA(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 RA(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=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function pd(e,t,n,o,r,s,a,i){let p=r.has(e.id),d=y("div","persona-border-b persona-border-persona-divider persona-text-xs");ss(d,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:()=>g(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(b)return d.appendChild(b),d}return d.appendChild(g()),d;function g(){let b=y("div",""),f=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=se(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&x.appendChild(C);let S=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=o.timestampFormat??"relative";S.textContent=M==="relative"?SA(e.timestamp,n):TA(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let T=AA(e.type,o.badgeColors),L=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=T.bg,L.style.color=T.text,L.style.borderColor=T.text+"50",L.textContent=e.type;let H=o.descriptionFields??CA,O=EA(e.payload,H),_=null;O&&(_=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),_.textContent=O);let U=y("div","persona-flex-1 persona-min-w-0"),z=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),Y=se("clipboard","12px","currentColor",1.5);return Y&&z.appendChild(Y),z.addEventListener("click",async A=>{A.stopPropagation(),await MA(kA(e)),z.innerHTML="";let G=se("check","12px","currentColor",1.5);G&&z.appendChild(G),setTimeout(()=>{z.innerHTML="";let Q=se("clipboard","12px","currentColor",1.5);Q&&z.appendChild(Q)},1500)}),f.appendChild(x),f.appendChild(S),P&&f.appendChild(P),f.appendChild(L),_&&f.appendChild(_),f.appendChild(U),f.appendChild(z),b.appendChild(f),p&&b.appendChild(RA(e,a,i)),b}}function lm(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",g=r?.features?.eventStream??{},b=s.find(x=>x.renderEventStreamView);if(b?.renderEventStreamView&&r){let x=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(x)return{element:x,update:()=>{},destroy:()=>{}}}return f();function f(){let x=g.classNames,C=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ss(C,x?.panel);let S=[],M="",P="",T=null,L=[],H={},O=0,_=Mi(),U=0,z=0,Y=!1,A=null,G=!1,Q=0,le=new Set,J=new Map,me="",ee="",ye=null,Z,ue,te,fe,be=null,he=null,Be=null;function rt(){let $=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(ss(K,x?.headerBar),a){he=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",be=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),be.textContent="-- tok/s",Be=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Be.style.display="none",Be.style.pointerEvents="none";let St=he,un=Be,wa=()=>{if(!un.textContent)return;let gn=St.getBoundingClientRect(),dt=$.getBoundingClientRect();un.style.left=`${gn.left-dt.left}px`,un.style.top=`${gn.bottom-dt.top+4}px`,un.style.display="block"},oe=()=>{un.style.display="none"};he.addEventListener("mouseenter",wa),he.addEventListener("mouseleave",oe),he.appendChild(be)}let de=y("div","persona-flex-1");Z=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ue=y("option","");Ue.value="",Ue.textContent="All events (0)",Z.appendChild(Ue),ue=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ue.type="button",ue.title="Copy All";let Pe=se("clipboard-copy","12px","currentColor",1.5);Pe&&ue.appendChild(Pe);let ze=y("span","persona-event-copy-all persona-text-xs");ze.textContent="Copy All",ue.appendChild(ze),he&&K.appendChild(he),K.appendChild(de),K.appendChild(Z),K.appendChild(ue);let je=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ss(je,x?.searchBar);let He=se("search","14px","var(--persona-muted, #9ca3af)",1.5),Se=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");He&&Se.appendChild(He),te=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ss(te,x?.searchInput),te.type="text",te.placeholder="Search event payloads...",fe=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),fe.type="button",fe.style.display="none";let nt=se("x","12px","currentColor",2);return nt&&fe.appendChild(nt),je.appendChild(Se),je.appendChild(te),je.appendChild(fe),$.appendChild(K),$.appendChild(je),Be&&$.appendChild(Be),$}let $e,Ve=s.find($=>$.renderEventStreamToolbar);Ve?.renderEventStreamToolbar&&r?$e=Ve.renderEventStreamToolbar({config:r,defaultRenderer:()=>rt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:K=>{M=K,ke(),Te()},onSearchChange:K=>{P=K,ke(),Te()}})??rt():$e=rt();let Le=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Le.style.display="none";function _e(){if(!a||!be||!he)return;let $=a(),K=LA($);be.textContent=K;let de=PA($);Be&&(Be.textContent=de,de||(Be.style.display="none")),he.setAttribute("aria-label",de?`Throughput: ${K}, ${de}`:`Throughput: ${K}`)}let we=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ae=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ae.style.height="100%";let Re=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ss(Re,x?.scrollIndicator),Re.style.display="none",Re.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let ct=se(d,"14px","currentColor",2);ct&&Re.appendChild(ct);let et=y("span","");et.textContent=c,Re.appendChild(et);let vt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");vt.style.display="none",we.appendChild(ae),we.appendChild(vt),we.appendChild(Re),C.setAttribute("tabindex","0"),C.appendChild($e),C.appendChild(Le),C.appendChild(we);function wn(){let $=t.getAll(),K={};for(let je of $)K[je.type]=(K[je.type]||0)+1;let de=Object.keys(K).sort(),Ue=de.length!==L.length||!de.every((je,He)=>je===L[He]),pe=!Ue&&de.some(je=>K[je]!==H[je]),Pe=$.length!==Object.values(H).reduce((je,He)=>je+He,0);if(!Ue&&!pe&&!Pe||(L=de,H=K,!Z))return;let ze=Z.value;if(Z.options[0].textContent=`All events (${$.length})`,Ue){for(;Z.options.length>1;)Z.remove(1);for(let je of de){let He=y("option","");He.value=je,He.textContent=`${je} (${K[je]||0})`,Z.appendChild(He)}ze&&de.includes(ze)?Z.value=ze:ze&&(Z.value="",M="")}else for(let je=1;je<Z.options.length;je++){let He=Z.options[je];He.textContent=`${He.value} (${K[He.value]||0})`}}function An(){let $=t.getAll();if(M&&($=$.filter(K=>K.type===M)),P){let K=P.toLowerCase();$=$.filter(de=>de.type.toLowerCase().includes(K)||de.payload.toLowerCase().includes(K))}return $}function Ze(){return M!==""||P!==""}function ke(){O=0,U=0,_.resume(),Re.style.display="none"}function ve($){le.has($)?le.delete($):le.add($),ye=$;let K=ae.scrollTop,de=_.isFollowing();G=!0,_.pause(),Te(),ae.scrollTop=K,de&&_.resume(),G=!1}function tt(){return oo(ae,50)}function Te(){z=Date.now(),Y=!1,_e(),wn();let $=t.getEvictedCount();$>0?(Le.textContent=`${$.toLocaleString()} older events truncated`,Le.style.display=""):Le.style.display="none",S=An();let K=S.length,de=t.getSize()>0;K===0&&de&&Ze()?(vt.textContent=P?`No events matching '${P}'`:"No events matching filter",vt.style.display="",ae.style.display="none"):(vt.style.display="none",ae.style.display=""),ue&&(ue.title=Ze()?`Copy Filtered (${K})`:"Copy All"),p&&!_.isFollowing()&&K>O&&(U+=K-O,et.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Re.style.display=""),O=K;let Ue=t.getAll(),pe=Ue.length>0?Ue[0].timestamp:0,Pe=new Set(S.map(He=>He.id));for(let He of le)Pe.has(He)||le.delete(He);let ze=M!==me||P!==ee,je=J.size===0&&S.length>0;if(ze||je||S.length===0){ae.innerHTML="",J.clear();let He=document.createDocumentFragment();for(let Se=0;Se<S.length;Se++){let nt=pd(S[Se],Se,pe,g,le,ve,s,r);J.set(S[Se].id,nt),He.appendChild(nt)}ae.appendChild(He),me=M,ee=P,ye=null}else{if(ye!==null){let Se=J.get(ye);if(Se&&Se.parentNode===ae){let nt=S.findIndex(St=>St.id===ye);if(nt>=0){let St=pd(S[nt],nt,pe,g,le,ve,s,r);ae.insertBefore(St,Se),Se.remove(),J.set(ye,St)}}ye=null}let He=new Set(S.map(Se=>Se.id));for(let[Se,nt]of J)He.has(Se)||(nt.remove(),J.delete(Se));for(let Se=0;Se<S.length;Se++){let nt=S[Se];if(!J.has(nt.id)){let St=pd(nt,Se,pe,g,le,ve,s,r);J.set(nt.id,St),ae.appendChild(St)}}}_.isFollowing()&&(ae.scrollTop=ae.scrollHeight)}function Ce(){if(Date.now()-z>=wA){A!==null&&(cancelAnimationFrame(A),A=null),Te();return}Y||(Y=!0,A=requestAnimationFrame(()=>{A=null,Te()}))}let re=($,K)=>{if(!ue)return;ue.innerHTML="";let de=se($,"12px","currentColor",1.5);de&&ue.appendChild(de);let Ue=y("span","persona-text-xs");Ue.textContent="Copy All",ue.appendChild(Ue),setTimeout(()=>{ue.innerHTML="";let pe=se("clipboard-copy","12px","currentColor",1.5);pe&&ue.appendChild(pe);let Pe=y("span","persona-text-xs");Pe.textContent="Copy All",ue.appendChild(Pe),ue.disabled=!1},K)},Ae=async()=>{if(ue){ue.disabled=!0;try{let $;Ze()?$=S:n?($=await n(),$.length===0&&($=t.getAll())):$=t.getAll();let K=$.map(de=>{try{return JSON.parse(de.payload)}catch{return de.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),re("check",1500)}catch{re("x",1500)}}},Sn=()=>{Z&&(M=Z.value,ke(),Te())},ne=()=>{!te||!fe||(fe.style.display=te.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{P=te.value,ke(),Te()},150))},E=()=>{!te||!fe||(te.value="",P="",fe.style.display="none",T&&clearTimeout(T),ke(),Te())},I=()=>{if(G)return;let $=ae.scrollTop,{action:K,nextLastScrollTop:de}=ki({following:_.isFollowing(),currentScrollTop:$,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=de,K==="resume"?(_.resume(),U=0,Re.style.display="none"):K==="pause"&&(_.pause(),p&&(et.textContent=c,Re.style.display=""))},h=$=>{let K=Li({following:_.isFollowing(),deltaY:$.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});K==="pause"?(_.pause(),p&&(et.textContent=c,Re.style.display="")):K==="resume"&&(_.resume(),U=0,Re.style.display="none")},W=()=>{p&&(ae.scrollTop=ae.scrollHeight,_.resume(),U=0,Re.style.display="none")},R=$=>{let K=$.target;if(!K||K.closest("button"))return;let de=K.closest("[data-event-id]");if(!de)return;let Ue=de.getAttribute("data-event-id");Ue&&ve(Ue)},B=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),te?.focus(),te?.select();return}$.key==="Escape"&&(te&&document.activeElement===te?(E(),te.blur(),C.focus()):o&&o())};ue&&ue.addEventListener("click",Ae),Z&&Z.addEventListener("change",Sn),te&&te.addEventListener("input",ne),fe&&fe.addEventListener("click",E),ae.addEventListener("scroll",I),ae.addEventListener("wheel",h,{passive:!0}),ae.addEventListener("click",R),Re.addEventListener("click",W),C.addEventListener("keydown",B);function V(){T&&clearTimeout(T),A!==null&&(cancelAnimationFrame(A),A=null),Y=!1,J.clear(),ue&&ue.removeEventListener("click",Ae),Z&&Z.removeEventListener("change",Sn),te&&te.removeEventListener("input",ne),fe&&fe.removeEventListener("click",E),ae.removeEventListener("scroll",I),ae.removeEventListener("wheel",h),ae.removeEventListener("click",R),Re.removeEventListener("click",W),C.removeEventListener("keydown",B)}return{element:C,update:Ce,destroy:V}}}function ud(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=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},p=g=>{let b=g;return s.findIndex(f=>f===b||f.contains(b))},d=g=>{let b=p(g.target);if(b<0)return;let f=b;if(g.key===r)f=Math.min(b+1,s.length-1);else if(g.key===o)f=Math.max(b-1,0);else if(g.key==="Home")f=0;else if(g.key==="End")f=s.length-1;else return;g.preventDefault(),f!==b&&t.onSelect(f)},c=g=>{let b=p(g.target);b>=0&&i(s[b])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(g,b){if(s=g,g.forEach((f,x)=>{f.setAttribute("role","tab");let C=x===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&x===0?0:-1}),a){let f=(b>=0?g[b]:void 0)??g[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function cm(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=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:g}=d(n?.tabFade),b=typeof document<"u"?y("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"),x.classList.remove("persona-artifact-drawer-open"),G?.hide()};b&&b.addEventListener("click",()=>{f(),t.onDismiss?.()});let x=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");x.setAttribute("data-persona-theme-zone","artifact-pane"),r&&x.classList.add("persona-artifact-pane-document");let C=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let S=y("span","persona-text-xs persona-font-medium persona-truncate");S.textContent=s;let M=lt({icon:"x",label:a});M.addEventListener("click",()=>{f(),t.onDismiss?.()});let P="rendered",T=Po({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=>{P=ne==="source"?"source":"rendered",re()}}),L=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=n?.documentToolbarShowCopyLabel===!0,O=n?.documentToolbarShowCopyChevron===!0,_=n?.documentToolbarCopyMenuItems,U=!!(O&&_&&_.length>0),z=null,Y,A=null,G=null;if(r&&(H||O)&&!U){if(Y=H?Lo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O){let ne=se("chevron-down",14,"currentColor",2);ne&&Y.appendChild(ne)}}else r&&U?(z=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=H?Lo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=lt({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"}}),z.append(Y,A)):r?Y=lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Y=lt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Y.classList.add("persona-hidden"));let Q=r?lt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):lt({icon:"refresh-cw",label:"Refresh"}),le=r?lt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):lt({icon:"x",label:a}),J=lt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&J.classList.add("persona-hidden");let me=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ee=e.features?.artifacts?.toolbarActions??[],ye=()=>{let ne=we.find(W=>W.id===ae)??we[we.length-1],E=ne?.id??null,I=ne?.artifactType==="markdown"?ne.markdown??"":"",h=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:I,jsonPayload:h,id:E}},Z=async()=>{let ne=we.find(E=>E.id===ae)??we[we.length-1];try{await navigator.clipboard.writeText(sa(ne))}catch{}};if(Y.addEventListener("click",async()=>{let ne=n?.onDocumentToolbarCopyMenuSelect;if(ne&&U){let{markdown:E,jsonPayload:I,id:h}=ye();try{await ne({actionId:"primary",artifactId:h,markdown:E,jsonPayload:I})}catch{}return}await Z()}),A&&_?.length){let ne=()=>x.closest("[data-persona-root]")??document.body,E=()=>{G=mr({items:_.map(I=>({id:I.id,label:I.label})),onSelect:async I=>{let{markdown:h,jsonPayload:W,id:R}=ye(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:I,artifactId:R,markdown:h,jsonPayload:W}):I==="markdown"||I==="md"?await navigator.clipboard.writeText(h):I==="json"||I==="source"?await navigator.clipboard.writeText(W):await navigator.clipboard.writeText(h||W)}catch{}},anchor:z??A,position:"bottom-right",portal:ne()})};x.isConnected?E():requestAnimationFrame(E),A.addEventListener("click",I=>{I.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),le.addEventListener("click",()=>{f(),t.onDismiss?.()});let ue=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),z?L.append(z,Q,le):L.append(Y,Q,le),L.insertBefore(me,le),L.insertBefore(J,le),C.append(T.element,ue,L);else{let ne=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ne.append(Y,me,J,M),C.appendChild(S),C.appendChild(ne)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let te=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&te.style.setProperty("--persona-artifact-tab-fade-size",p);let fe=e.features?.artifacts?.renderTabBar,be=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=ud(te,{onSelect:ne=>t.onSelect(we[ne].id)}),Be=ne=>{let E=ne.scrollWidth-ne.clientWidth,I=E>1,h=Math.abs(ne.scrollLeft);ne.classList.toggle("persona-artifact-tab-fade-start",c&&I&&h>1),ne.classList.toggle("persona-artifact-tab-fade-end",g&&I&&h<E-1)},rt=0,$e=()=>{if(rt)return;let ne=()=>{rt=0,Be(te)};rt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ne):setTimeout(ne,0)};te.addEventListener("scroll",()=>$e(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Be(te)).observe(te);let Ve=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Le=()=>{Ve.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Le):setTimeout(Le,0)};if(i){for(let ne of[te,be])ne.style.paddingLeft=i,ne.style.paddingRight=i;Ve.style.padding=i}x.appendChild(C),x.appendChild(te),x.appendChild(be),x.appendChild(Ve);let we=[],ae=null,Re=!1,ct=!1,et=!0,vt=!1,wn=null,An="",Ze=null,ke=!1,ve=ne=>ne.artifactType==="markdown"&&!!ne.file||r?P:"rendered",tt=ne=>{r||(ne&&!ke?(C.insertBefore(T.element,S),ke=!0):!ne&&ke&&(T.element.remove(),ke=!1))},Te=()=>ae&&we.find(ne=>ne.id===ae)||we[we.length-1],Ce=()=>{let ne=oa(Te());if(!ne){me.replaceChildren();return}let E=ee.filter(I=>I.visible===void 0||I.visible(ne)).map(I=>Xr(I,{documentChrome:r,onClick:()=>{let h=oa(Te());if(h)try{Promise.resolve(I.onClick(h)).catch(()=>{})}catch{}}}));me.replaceChildren(...E)},re=()=>{Ce();let ne=r&&we.length<=1,E=!!fe;if(te.classList.toggle("persona-hidden",ne||E),be.classList.toggle("persona-hidden",ne||!E),E&&fe){let W=we.map(R=>R.id).join("|")+" "+(ae??"");if(W!==An){An=W;let R=fe({records:we,selectedId:ae,onSelect:t.onSelect});be.firstElementChild!==R&&be.replaceChildren(R)}}else{he.beforeRender(),te.replaceChildren();let W=[],R=-1;for(let[B,V]of we.entries()){let $=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");$.type="button";let K=V.artifactType==="markdown"?V.file:void 0,de=K?Nn(K.path):V.title||V.id.slice(0,8),Ue=K?.path||V.title||de;$.textContent=de,$.title=Ue,$.setAttribute("aria-label",Ue),V.id===ae&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=B),$.addEventListener("click",()=>t.onSelect(V.id)),te.appendChild($),W.push($)}if(he.render(W,R),R>=0&&ae!==wn){wn=ae;let B=W[R];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}Be(te)}let I=ae&&we.find(W=>W.id===ae)||we[we.length-1];if(!I){Ve.replaceChildren(),Ze=null,tt(!1);return}let h=I.artifactType==="markdown"?I.file:void 0;if(tt(!!h&&gr(h)!=="other"),r){let W=h?Mo(h):I.artifactType==="markdown"?"MD":I.component??"Component",R=(I.title||"Document").trim(),B=h?Nn(h.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ue.textContent=`${B} \xB7 ${W}`}else S.textContent=h?Nn(h.path):s;Ze?(Ze.el.parentElement!==Ve&&Ve.replaceChildren(Ze.el),Ze.update(I)):(Ze=Ti(I,{config:e,resolveViewMode:ve}),Ve.replaceChildren(Ze.el)),Ve.classList.toggle("persona-artifact-content-flush",!!Ve.querySelector(".persona-code-pre"))},Ae=()=>{let ne=we.length>0;if(x.classList.toggle("persona-hidden",!ne),b){let h=((typeof x.closest=="function"?x.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ne&&h&&Re?(b.classList.remove("persona-hidden"),x.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),x.classList.remove("persona-artifact-drawer-open"))}},Sn=()=>{vt=!1,re(),Ae()};return{element:x,backdrop:b,update(ne){let E=ne.selectedId??ne.artifacts[ne.artifacts.length-1]?.id??null,I=E!==ae;we=ne.artifacts,ae=E,we.length>0&&(Re=!0),vt=!0,et&&Sn(),I&&Le()},setMobileOpen(ne){Re=ne,!ne&&b?(b.classList.add("persona-hidden"),x.classList.remove("persona-artifact-drawer-open")):Ae()},setExpanded(ne){ne!==ct&&(ct=ne,_e());let E=se(ne?"minimize":"maximize",16,"currentColor",2);E&&J.replaceChildren(E);let I=ne?"Collapse artifacts panel":"Expand artifacts panel";J.setAttribute("aria-label",I),J.title=I},setExpandToggleVisible(ne){J.classList.toggle("persona-hidden",!ne)},setCopyButtonVisible(ne){r||Y.classList.toggle("persona-hidden",!ne)},setCustomActions(ne){ee=ne,Ce()},setTabFade(ne){let E=d(ne);E.start===c&&E.end===g||(c=E.start,g=E.end,Be(te))},setRenderTabBar(ne){ne!==fe&&(fe=ne,An="",re())},setVisible(ne){ne!==et&&(et=ne,ne&&vt&&Sn())}}}function Qt(e){return e?.features?.artifacts?.enabled===!0}function dm(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Qt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),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 IA(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 pm=["panel","seamless","detached"];function gd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&pm.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function fd(e){return!e||!Qt(e)?!1:gd(e)==="detached"}function va(e,t){if(!Qt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),IA(e),dm(e,t);return}let n=t.features?.artifacts?.layout,o=gd(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?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),dm(e,t)}function xa(e,t){for(let i of pm)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Qt(t))return;let n=t.features?.artifacts?.layout,o=gd(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 um(e,t){return!t||!Qt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var WA=new Set(["__proto__","prototype","constructor"]),HA=new Set(["collapsed","card","panel","inline"]),gm=new Set(["markdown","component"]),BA=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,xr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yi=e=>!WA.has(e),md=e=>typeof e=="string"&&HA.has(e),Cr=e=>Object.keys(e).length>0;function $n(e,t,n,o){e.push({path:t,code:n,message:o})}var DA="Ignored because this key is not part of the persisted preference schema.",Ji="Ignored an unsupported value.",OA="Expected collapsed, panel, or inline.",NA='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',fm={kind:"mode",message:Ji},as={kind:"string",message:"Expected a CSS length string."},ro={kind:"boolean"},FA={paneWidth:as,paneMaxWidth:as,paneMinWidth:as,expandedPanelWidth:as,resizableMinWidth:as,resizableMaxWidth:as,expandLauncherPanelWhenOpen:ro,resizable:ro},_A={kind:"object",message:"Expected a preference object.",children:{showToolCalls:ro,showReasoning:ro,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ji},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ji},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ji},expandable:ro,grouped:ro}},reasoningDisplay:{kind:"object",children:{expandable:ro,activePreview:ro}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:fm,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:fm,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:gm,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:gm}}},filePreview:{kind:"object",children:{enabled:ro}},layout:{kind:"object",children:FA}}}}};function mm(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:$n(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:$n(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:$n(o,n,"invalid_value",t.message);case"mode":return md(e)?ln(e):$n(o,n,"invalid_value",t.message);case"modeMap":{if(!xr(e))return $n(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 p=r?a:rr(a);Yi(a)&&(r?r.has(a):BA.test(p))?md(i)?s[p]=ln(i):$n(o,`${n}.${a}`,"invalid_value",OA):$n(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":NA)}return Cr(s)?s:void 0}case"object":{if(t.bareMode&&md(e))return ln(e);if(!xr(e))return $n(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))&&$n(o,s(i),"unknown_key",DA);let a={};for(let i of r){let p=t.children[i],d=mm(e[i],p,s(i),o);if(p.deprecated&&e[i]!==void 0&&$n(o,s(i),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??i,g=a[c];a[c]=xr(g)&&xr(d)?{...g,...d}:d}return Cr(a)?a:void 0}}}function hm(e){let t=[];return{preferences:(e===null?void 0:mm(e,_A,"",t))??{},issues:t}}function is(e){if(Array.isArray(e))return e.map(is);if(!xr(e))return e;let t={};for(let[n,o]of Object.entries(e))Yi(n)&&o!==void 0&&(t[n]=is(o));return t}function ym(e,t){let n=is(e);for(let[o,r]of Object.entries(t)){if(!Yi(o)||r===void 0)continue;let s=n[o];n[o]=xr(s)&&xr(r)?ym(s,r):is(r)}return n}function $A(e){let t={},n;for(let r of e){let s=hm(r).preferences;n=bm(n,s.artifacts?.display),t=ym(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function jA(e,t){if(t===void 0)return e===void 0?void 0:is(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}:{},...Cr(r)?{byMediaType:r}:{}};return Cr(s)?s:void 0}function bm(e,t){if(t===void 0)return e===void 0?void 0:is(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=jA(n.files,t.files),a={...o?{default:o}:{},...Cr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Cr(a)?a:void 0}function vm(e={},t){let n=$A(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=bm(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 Xi(e){let t=e.preferences;return!t||!Cr(t)?e:{...e,features:vm(e.features??{},[t])}}function UA(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 zA(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 qA(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function VA(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function hd(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 xm(e,t,n,o,r,s){let a=UA(r,200),i=VA(t,n,o,200);i=Math.max(a,i);let p=zA(s);return p!==null&&(i=Math.min(i,p)),qA(e,a,i)}var Cm={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"}},yd=(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=Cm[a]??Cm.init;s.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),d=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let x=y("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,p.appendChild(x)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{let C=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${x.name}`;let S=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");S.textContent=x.label,C.appendChild(S);let M=x.type??"text",P;M==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=M),P.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",P.id=`${t.id}-${a}-${x.name}`,P.name=x.name,P.placeholder=x.placeholder??"",x.required&&(P.required=!0),C.appendChild(P),c.appendChild(C)});let g=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",g.appendChild(b),g.appendChild(f),c.appendChild(g),s.replaceChildren(p,c),c.addEventListener("submit",async x=>{x.preventDefault();let C=n.formEndpoint??"/form",S=new FormData(c),M={};S.forEach((P,T)=>{M[T]=P}),M.type=a,f.disabled=!0,b.textContent="Submitting\u2026";try{let P=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let T=await P.json();b.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await o.sendMessage(String(T.nextPrompt))}catch(P){b.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var bd=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()}},Qi=new bd;var wm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KA=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Am=(e,t,n)=>{if(!wm(e)||!wm(t)||KA.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]=Am(e[r],t[r],s)}return o};function Zi(e,t){let n=Am(e,t,"");return ta(n)}var Sm=()=>{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 GA=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},JA=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},el=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=GA(e),n=JA(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}},vd=e=>typeof e=="string"?e:e==null?"":String(e),ls={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vd(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=vd(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:vd(n.text)}}},Tm=e=>Array.isArray(e)?e.map(t=>String(t)):[],tl=e=>{let t=new Set(Tm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Tm(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let p={action:i,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},g=d(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!g)continue;if(g.handled){let b=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:b,resubmit:g.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var YA=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}},XA=e=>e.map(t=>({...t,streaming:!1})),QA=e=>e.map(t=>({...t,status:"complete"})),xd=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?YA(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?XA(n.messages):void 0,artifacts:n.artifacts?QA(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)}}}};import{parse as ZA,STR as eS,OBJ as tS}from"partial-json";function nS(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function oS(e,t){if(!nS(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 Cd(){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=ZA(n,eS|tS),s=oS(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function rS(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function wd(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Fn.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 sS(){let e=Cd();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Em(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 nl(e){let t=Em(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 Ad(e){let t=Em(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 aS=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Sd(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=aS}=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 g=null,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,f.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let O=1;O<=5;O++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-star-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`${O} star${O>1?"s":""}: ${d[O-1]}`),_.title=d[O-1],_.dataset.rating=String(O),_.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=z,P.forEach((U,q)=>{let ee=q<z;U.classList.toggle("selected",ee),U.setAttribute("aria-checked",q===z-1?"true":"false")})}),P.push(w),E.appendChild(w)}b.appendChild(E);let W=null;if(d){let z=document.createElement("div");z.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"),z.appendChild(W),b.appendChild(z)}let M=document.createElement("div");M.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 z=W?.value.trim()||void 0;await t(u,z),c.remove()}catch(z){F.disabled=!1,F.textContent=a,console.error("[CSAT Feedback] Failed to submit:",z)}}),M.appendChild(k),M.appendChild(F),b.appendChild(M),c.appendChild(b),c}function Lc(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 E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,y.appendChild(E),f.appendChild(y);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=p;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=c,W.appendChild(M),W.appendChild(k);let F=document.createElement("div");F.className="persona-feedback-numbers";let z=[];for(let D=0;D<=10;D++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${D} out of 10`),$.textContent=String(D),$.dataset.rating=String(D),D<=6?$.classList.add("persona-feedback-detractor"):D<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{b=D,z.forEach((X,ye)=>{X.classList.toggle("selected",ye===D),X.setAttribute("aria-checked",ye===D?"true":"false")})}),z.push($),F.appendChild($)}P.appendChild(W),P.appendChild(F),f.appendChild(P);let w=null;if(d){let D=document.createElement("div");D.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"),D.appendChild(w),f.appendChild(D)}let U=document.createElement("div");U.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=i,q.addEventListener("click",()=>{n?.(),u.remove()});let ee=document.createElement("button");return ee.type="button",ee.className="persona-feedback-btn persona-feedback-btn-submit",ee.textContent=a,ee.addEventListener("click",async()=>{if(b===null){F.classList.add("persona-feedback-shake"),setTimeout(()=>F.classList.remove("persona-feedback-shake"),500);return}ee.disabled=!0,ee.textContent="Submitting...";try{let D=w?.value.trim()||void 0;await t(b,D),u.remove()}catch(D){ee.disabled=!1,ee.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),U.appendChild(q),U.appendChild(ee),f.appendChild(U),u.appendChild(f),u}var Dr="persona-chat-history",ZC=30*1e3,ew=641,tw={"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 nw(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=tw[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 Pi(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 ow(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 rw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Rc=e=>!e||typeof e!="object"?{}:{...e},Zf=e=>e.map(t=>({...t,streaming:!1})),eg=(e,t,n)=>{let o=e?.markdown?hr(e.markdown):null,r=cs(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=$n()!==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?fp(a):a,u=o(c);p=r&&d?r(u):u}else p=jn(a);return p}};function tg(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=oe(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 sw=(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},aw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:sw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Ic=(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=Es(t),r=o.features;o=Ai(o);let s=Si.getForInstance(o.plugins),{plugin:a,teardown:i}=Pf();o.components&&Ln.registerAll(o.components);let d=Xf(),c=o.persistState===!1?null:o.storageAdapter??Tc(),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=Rc(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,E=l=>{u=l({...u})??{},Qi()},P=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Mi],W=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Br.message,Br.messageAndClick],M=Ei({parsers:P,handlers:W,getSessionMetadata:C,updateSessionMetadata:E,emit:d.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let k=o.launcher?.enabled??!0,F=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,w=F,U=k,q=o.layout?.header?.layout,ee=!1,D=()=>Co(o),$=()=>k||D(),X=D()?!1:k?F:!0,ye=!1,be=null,He=()=>{ye=!0,be&&clearTimeout(be),be=setTimeout(()=>{ye&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ye=!1)},1e4)},re=eg(o,M,He),me=o.features?.showReasoning??!0,Z=o.features?.showToolCalls??!0,ce=o.features?.showEventStreamToggle??!1,Q=o.features?.scrollToBottom??{},pe=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Ae=ce?new Us(he):null,at=o.features?.eventStream?.maxEvents??2e3,Me=ce?new js(at,Ae):null,Be=ce?new zs:null,Oe=null,ze=!1,Te=null,le=0;Ae?.open().then(()=>Me?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Pe={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)}},rt=o.statusIndicator??{},vt=l=>l==="idle"?rt.idleText??Wt.idle:l==="connecting"?rt.connectingText??Wt.connecting:l==="connected"?rt.connectedText??Wt.connected:l==="error"?rt.errorText??Wt.error:l==="paused"?rt.pausedText??Wt.paused:l==="resuming"?rt.resumingText??Wt.resuming:Wt[l];function kt(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 St=ff({config:o,showClose:$()}),{wrapper:De,panel:de,pillRoot:Ze}=St.shell,Re=St.panelElements,{container:fe,body:ae,messagesWrapper:Le,suggestions:it,textarea:ue,sendButton:we,sendButtonWrapper:te,composerForm:S,statusText:O,introTitle:v,introSubtitle:R,closeButton:T,iconHolder:I,headerTitle:K,headerSubtitle:B,header:j,footer:Y,actionsRow:Ke,rightActions:Ie}=Re,Xe=Re.leftActions,ot=Re.setSendButtonMode,V=Re.micButton,je=Re.micButtonWrapper,xe=Re.attachmentButton,Ue=Re.attachmentButtonWrapper,Fe=Re.attachmentInput,Bt=Re.attachmentPreviewsContainer;fe.classList.add("persona-relative"),ae.classList.add("persona-relative");let Ni=12,So=()=>Q.label??"",Gs=()=>Q.iconName??"arrow-down",Js=()=>Q.enabled!==!1,ln=()=>pe.mode??"anchor-top",Gn=()=>ln()==="follow"||ln()==="anchor-top"&&Vr,zc=()=>pe.anchorTopOffset??16,Og=()=>pe.restorePosition??"bottom",qc=()=>pe.pauseOnInteraction===!0,Vc=()=>pe.showActivityWhilePinned!==!1,Kc=()=>pe.announce===!0,Pt=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");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Or=m("span","persona-flex persona-items-center"),Fi=m("span",""),To=m("span","");To.setAttribute("data-persona-scroll-to-bottom-count",""),To.style.display="none",Pt.append(Or,Fi,To),fe.appendChild(Pt);let Jn=m("div","persona-stream-anchor-spacer");Jn.setAttribute("aria-hidden","true"),Jn.setAttribute("data-persona-anchor-spacer",""),Jn.style.flexShrink="0",Jn.style.pointerEvents="none",Jn.style.height="0px",ae.appendChild(Jn);let Mo=m("div","persona-sr-only");Mo.setAttribute("aria-live","polite"),Mo.setAttribute("aria-atomic","true"),Mo.setAttribute("role","status"),Mo.setAttribute("data-persona-live-region",""),Object.assign(Mo.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"}),fe.appendChild(Mo);let Nr=null,Xs=null,Gc=l=>{!Kc()||!l||(Xs=l,Nr===null&&(Nr=setTimeout(()=>{Nr=null,Xs&&Kc()&&(Mo.textContent=Xs),Xs=null},400)))},nr=()=>{let g=Y.style.display==="none"?0:Y.offsetHeight;Pt.style.bottom=`${g+Ni}px`};nr();let Jc=()=>{let l=!!So();Pt.setAttribute("aria-label",So()||"Jump to latest"),Pt.title=So(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Or.innerHTML="";let g=oe(Gs(),"14px","currentColor",2);g?(Or.appendChild(g),Or.style.display=""):Or.style.display="none",Fi.textContent=So(),Fi.style.display=l?"":"none"};Jc();let Tt=null,Zt=null,Xc=null,Yc=s.find(l=>l.renderHeader);if(Yc?.renderHeader){let l=Yc.renderHeader({config:o,defaultRenderer:()=>{let g=wo({config:o,showClose:$()});return kr(fe,g,o),g.header},onClose:()=>ut(!1,"user")});if(l){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),j=l,St.header.element=l)}}let _i=()=>{if(!Me)return;if(ze=!0,!Oe&&Me&&(Oe=Hf({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Fr(),config:o,plugins:s,getThroughput:()=>Be?.getMetric()??{status:"idle"}})),Oe&&(ae.style.display="none",Y.parentNode?.insertBefore(Oe.element,Y),Oe.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&et.classList.add(h))}let l=()=>{if(!ze)return;let g=Date.now();g-le>=200&&(Oe?.update(),le=g),Te=requestAnimationFrame(l)};le=0,Te=requestAnimationFrame(l),tn(),d.emit("eventStream:opened",{timestamp:Date.now()})},Fr=()=>{if(ze){if(ze=!1,Oe&&Oe.element.remove(),ae.style.display="",et){et.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&et.classList.remove(g))}Te!==null&&(cancelAnimationFrame(Te),Te=null),tn(),d.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(ce){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:"");et=m("button",g),et.style.width="28px",et.style.height="28px",et.style.color=Jt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let h=oe("activity","18px","currentColor",1.5);h&&et.appendChild(h);let x=Re.clearChatButtonWrapper,A=Re.closeButtonWrapper,L=x||A;L&&L.parentNode===j?j.insertBefore(et,L):j.appendChild(et),et.addEventListener("click",()=>{ze?Fr():_i()})}let Ng=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??qn).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(A)}},Qc=s.find(l=>l.renderComposer);if(Qc?.renderComposer){let l=o.composer,g=Qc.renderComposer({config:o,defaultRenderer:()=>_s({config:o}).footer,onSubmit:h=>{if(!_||_.isStreaming())return;let x=h.trim(),A=Tt?.hasAttachments()??!1;if(!x&&!A)return;kd();let L;A&&(L=[],L.push(...Tt.getContentParts()),x&&L.push(zo(x))),_.sendMessage(x,{contentParts:L}),A&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.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?()=>{Xc?.()}:void 0});g&&(St.replaceComposer(g),Y=St.composer.footer)}let Fg=l=>{let g=(...ge)=>{for(let se of ge){let Ce=l.querySelector(se);if(Ce)return Ce}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),J=l.querySelector("[data-persona-composer-status]");h&&(S=h),x&&(ue=x),A&&(we=A),L&&(V=L,je=L.parentElement),J&&(O=J);let N=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(it=N);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(xe=G,Ue=G.parentElement),Fe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Bt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(Ke=ie),Xe=g(".persona-widget-composer__left-actions")};Ng(Y),Fg(Y);let Xn=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Xn&&(Le.style.maxWidth=Xn,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%"),Xn&&S&&!D()&&(S.style.maxWidth=Xn,S.style.marginLeft="auto",S.style.marginRight="auto"),Xn&&it&&!D()&&(it.style.maxWidth=Xn,it.style.marginLeft="auto",it.style.marginRight="auto"),Xn&&Bt&&!D()&&(Bt.style.maxWidth=Xn,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Bt){Tt=wr.fromConfig(o.attachments),Tt.setPreviewsContainer(Bt),Fe.addEventListener("change",h=>{let x=h.target;Tt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,g=tg(l);fe.appendChild(g)}let _g=()=>Zt?.prefetch();if(o.contextMentions?.enabled&&ue&&(Zt=bu({config:o,textarea:ue,anchor:S??ue,getMessages:()=>_.getMessages(),liveRegionHost:fe}),Zt)){let l=ue;l.parentElement?.insertBefore(Zt.contextRow,l);let g=Zt.affordanceButtons;for(let h=g.length-1;h>=0;h--){let x=g[h];Xe?Xe.insertBefore(x,Xe.firstChild):S?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Le;case"footer-top":return it;case"composer":return S;case"footer-bottom":return O;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")j.insertBefore(A,j.firstChild);else if(x==="header-right")j.appendChild(A);else{let L=j.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(A,L.nextSibling):j.appendChild(A)}break;case"body-top":{let L=ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");L?L.replaceWith(A):ae.insertBefore(A,ae.firstChild);break}case"body-bottom":ae.appendChild(A);break;case"footer-top":it.replaceWith(A);break;case"footer-bottom":O.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(l))if(A)try{let L=A({config:o,defaultContent:()=>g(x)});L&&h(x,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,L)}})();let Zc=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 L=h.getAttribute("data-bubble-type");if(L==="reasoning")Lr.has(A)?Lr.delete(A):Lr.add(A),xf(A,x);else if(L==="tool")Rr.has(A)?Rr.delete(A):Rr.add(A),Cf(A,x,o);else if(L==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Yo.get(A)??N;Yo.set(A,!G),Tf(A,x,o)}Lo.delete(A)};Le.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zc(l))}),Le.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zc(l))}),Le.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let h=Le.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),L=qu(A);!L||L===A||(g.setData("text/plain",L),l.preventDefault())});let $i=new Map,ed=null,td="idle",$g={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},jg=(l,g)=>{let{icon:h,label:x}=$g[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=oe(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},nd=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;jg(g,x&&x===ed?td:"idle")})};Le.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 L=h.getAttribute("data-action");if(L==="copy"){let N=_.getMessages().find(G=>G.id===A);if(N&&Pe.onCopy){let G=N.content||"";navigator.clipboard.writeText(G).then(()=>{h.classList.add("persona-message-action-success");let ie=oe("check",14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ge=oe("copy",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))},2e3)}).catch(ie=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ie)}),Pe.onCopy(N)}}else if(L==="read-aloud")_.toggleReadAloud(A);else if(L==="upvote"||L==="downvote"){let N=($i.get(A)??null)===L,G=L==="upvote"?"thumbs-up":"thumbs-down";if(N){$i.delete(A),h.classList.remove("persona-message-action-active");let ie=oe(G,14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie))}else{let ie=L==="upvote"?"downvote":"upvote",ge=x.querySelector(`[data-action="${ie}"]`);if(ge){ge.classList.remove("persona-message-action-active");let tt=oe(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(ge.innerHTML="",ge.appendChild(tt))}$i.set(A,L),h.classList.add("persona-message-action-active");let se=oe(G,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(se)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ve=_.getMessages().find(ft=>ft.id===A);Ve&&Pe.onFeedback&&Pe.onFeedback({type:L,messageId:Ve.id,message:Ve})}}}),Le.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 L=h.getAttribute("data-approval-action");if(!L)return;let J=L==="approve"?"approved":"denied",G=_.getMessages().find(ge=>ge.id===A);if(!G?.approval)return;let ie=x.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?_.resolveWebMcpApproval(A,J):_.resolveApproval(G.approval,J)});let Ye=null,_r=null,$r=()=>{},jr="none",Ys=null,hn={artifacts:[],selectedId:null},Hn=!1,yn=!1,Ur=!1,or=!1,od=()=>or||hn.artifacts.some(l=>Un(o.features?.artifacts,l)==="panel"),Qs=()=>hn.artifacts.length>0&&!Hn&&od(),ct={current:null},ji=(l,g)=>{let h=_.getArtifactById(g),x=h?.markdown,A=h?.title||"artifact",L=h?.file,J=h?.artifactType??"markdown";if(!x){let ie=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ie){let se=_.getMessages().find(Ce=>Ce.id===ie);if(se?.rawContent)try{let Ce=JSON.parse(se.rawContent);x=Ce?.props?.markdown,A=Ce?.props?.title||A,Ce?.props?.file&&typeof Ce.props.file=="object"&&(L=Ce.props.file),!h&&typeof Ce?.props?.artifactType=="string"&&(J=Ce.props.artifactType)}catch{}}}return{markdown:x,title:A,file:L,artifactType:J}};Le.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:L,title:J,file:N}=ji(h,x);if(!L)return;let{filename:G,mime:ie,content:ge}=ku({title:J,markdown:L,file:N}),se=new Blob([ge],{type:ie}),Ce=URL.createObjectURL(se),Ve=document.createElement("a");Ve.href=Ce,Ve.download=G,Ve.click(),URL.revokeObjectURL(Ce)}),Le.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]"),L=A?null:h.closest("[data-open-artifact]"),J=A?A.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,G=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ft=>ft.id===x);if(!G)return;let{markdown:ie,title:ge,file:se,artifactType:Ce}=ji(h,J??""),Ve={artifactId:J,title:ge,artifactType:Ce,markdown:ie,file:se};try{Promise.resolve(G.onClick(Ve)).catch(()=>{})}catch{}}),Le.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),L="";if(A)L=Is(A);else{let{markdown:J,file:N,artifactType:G}=ji(h,x);G==="markdown"&&(L=Is({id:x,artifactType:"markdown",status:"complete",markdown:J??"",...N?{file:N}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let J=oe("check",16,"currentColor",2);J&&(h.replaceChildren(J),setTimeout(()=>{let N=oe("copy",16,"currentColor",2);N&&h.replaceChildren(N)},1500))}).catch(()=>{})}),Le.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||(Hn=!1,or=!0,yn=!0,Ur=!0,_.selectArtifact(x),Bn())}),Le.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(),Hn=!1,or=!0,_.selectArtifact(x),Bn())}),Le.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 rr=Re.composerOverlay,sr=(l,g,h)=>{let x=g.trim();if(!x||!ct.current)return;let A=l.getAttribute("data-tool-call-id")??"",L=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:L,source:h.source},bubbles:!0,composed:!0})),jo(rr,A);let J=ct.current.getMessages().find(N=>N.toolCall?.id===A);J?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(J,h.structured??x):ct.current.sendMessage(x)},Eo=l=>{let g=ct.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:Ra(l,x),currentIndex:gn(l)})},rd=l=>Object.entries(l).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ui=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=gn(l),h=br(l);if(g>=h-1)return;let x=ct.current?.getMessages().find(A=>A.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(Ia(l,x,o,g+1),Eo(l))};rr.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 L=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),jo(rr,L);let J=ct.current?.getMessages().find(N=>N.toolCall?.id===L);J?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(J),ct.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(A==="pick"){let L=h.getAttribute("data-option-label");if(!L)return;let J=x.getAttribute("data-multi-select")==="true",N=co(x);if(N&&J){let G=$o(x)[gn(x)],ie=new Set(Array.isArray(G)?G:[]);ie.has(L)?ie.delete(L):ie.add(L),po(x,Array.from(ie)),Eo(x);return}if(N){po(x,L),Eo(x),Ui(x);return}if(J){let G=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",G?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!G);let ie=x.querySelector('[data-ask-user-action="submit-multi"]');ie&&(ie.disabled=Al(x).length===0);return}sr(x,L,{source:"pick",values:[L]});return}if(A==="submit-multi"){let L=Al(x);if(L.length===0)return;sr(x,L.join(", "),{source:"multi",values:L});return}if(A==="open-free-text"){let L=x.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.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 J=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(co(x)){po(x,J.trim()),Eo(x),Ui(x);return}sr(x,J,{source:"free-text"});return}if(A==="next"||A==="back"){if(!ct.current)return;let L=x.getAttribute("data-tool-call-id")??"",J=ct.current.getMessages().find(se=>se.toolCall?.id===L);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let se=$o(x)[gn(x)];(typeof se!="string"||se!==G)&&po(x,G)}let ie=A==="next"?1:-1,ge=gn(x)+ie;Ia(x,J,o,ge),Eo(x);return}if(A==="submit-all"){if(!ct.current)return;let L=x.getAttribute("data-tool-call-id")??"",J=ct.current.getMessages().find(se=>se.toolCall?.id===L);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&po(x,G);let ie=Ra(x,J);ct.current.persistAskUserQuestionProgress(J,{answers:ie,currentIndex:gn(x)});let ge=rd(ie);sr(x,ge||"(submitted)",{source:"submit-all",structured:ie});return}if(A==="skip"){if(!ct.current)return;let L=x.getAttribute("data-tool-call-id")??"",J=ct.current.getMessages().find(Ce=>Ce.toolCall?.id===L);if(!J)return;let N=co(x),G=gn(x),ie=br(x),ge=G>=ie-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),jo(rr,L),J.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(J),ct.current.resolveAskUserQuestion(J,"(dismissed)"));return}po(x,"");let se=x.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),ge){let Ce=Ra(x,J),Ve=rd(Ce);sr(x,Ve||"(skipped)",{source:"submit-all",structured:Ce});return}Ia(x,J,o,G+1),Eo(x);return}}),rr.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(co(x)){po(x,A.trim()),Eo(x),Ui(x);return}sr(x,A,{source:"free-text"})}});let sd=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=rr.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),L=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];L&&(l.preventDefault(),L.click())};document.addEventListener("keydown",sd);let Yn=null,xt=null,zr=null,Zs=null,zi=()=>{},ad=!1,ea="",ta="";function qi(){Zs?.(),Zs=null}let id=()=>{if(!Yn||!xt)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){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=Yn.firstElementChild;if(!x||x===xt)return;let A=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${A}px`,xt.style.zIndex="5";let L=Cc(Yn,g),J=x.offsetWidth+L/2-A/2;xt.style.left=`${Math.max(0,J)}px`},na=()=>{},Ug=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>h?!1:k||Ht(o)},oa=()=>!Xt(o)||!Qs()||e.classList.contains("persona-artifact-narrow-host")||Ug()||(e.ownerDocument.defaultView??window).innerWidth<ew?"none":vc(o)?"detached":"welded",Bn=()=>{if(!Ye||!Xt(o))return;qs(e,o),Vs(e,o),na();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let h=Qs();Ye.setVisible(h),Ye.update(hn),Hn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),yn=!1,Ur=!1):hn.artifacts.length>0&&od()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),yn=!1,Ur=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(x),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Ur&&(yn=!1),yn!==ad){let L=Ye.element;yn?(ea=L.style.width,ta=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(ea&&(L.style.width=ea),ta&&(L.style.maxWidth=ta),ea="",ta=""),ad=yn}e.classList.toggle("persona-artifact-expanded",yn),Ye.setExpanded(yn);let A=oa();A!==jr&&(jr=A,$r()),zi()};if(Xt(o)){de.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(fe),Ye=Bf(o,{onSelect:h=>ct.current?.selectArtifact(h),onDismiss:()=>{Hn=!0,Bn()},onToggleExpand:()=>{let h=!yn,x=hn.selectedId??hn.artifacts[hn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(yn=h,h||(Ur=!1),Bn())}}),Ye.element.classList.add("persona-hidden"),Yn=g,g.appendChild(l),g.appendChild(Ye.element),Ye.backdrop&&de.appendChild(Ye.backdrop),de.appendChild(g),zi=()=>{if(!Yn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){zr?.(),zr=null,qi(),xt&&(xt.remove(),xt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!xt){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,L=A.defaultView??window,J=N=>{if(!Ye||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;N.preventDefault(),qi();let G=N.clientX,ie=Ye.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,se=Ve=>{let ft=Yn.getBoundingClientRect().width,tt=e.classList.contains("persona-artifact-welded-split"),nn=Cc(Yn,L),Mt=tt?0:x.getBoundingClientRect().width||6,Rt=ie-(Ve.clientX-G),H=Vf(Rt,ft,nn,Mt,ge?.resizableMinWidth,ge?.resizableMaxWidth);Ye.element.style.width=`${H}px`,Ye.element.style.maxWidth="none",id()},Ce=()=>{A.removeEventListener("pointermove",se),A.removeEventListener("pointerup",Ce),A.removeEventListener("pointercancel",Ce),Zs=null;try{x.releasePointerCapture(N.pointerId)}catch{}};Zs=Ce,A.addEventListener("pointermove",se),A.addEventListener("pointerup",Ce),A.addEventListener("pointercancel",Ce);try{x.setPointerCapture(N.pointerId)}catch{}};x.addEventListener("pointerdown",J),xt=x,Yn.insertBefore(x,Ye.element),zr=()=>{x.removeEventListener("pointerdown",J)}}if(xt){let x=Qs();xt.classList.toggle("persona-hidden",!x),id()}},na=()=>{if(!k||!Ye||(o.launcher?.sidebarMode??!1)||Ht(o)&&sn(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=L||!Nf(o,k))return;let J=o.launcher?.width??o.launcherWidth??mn,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Qs()?(de.style.width=N,de.style.maxWidth=N):(de.style.width=J,de.style.maxWidth=J)},typeof ResizeObserver<"u"&&(_r=new ResizeObserver(()=>{Bn()}),_r.observe(de))}else de.appendChild(fe);D()&&Ze&&(Re.peekBanner&&Ze.appendChild(Re.peekBanner),Ze.appendChild(Y)),e.appendChild(De),Ze&&e.appendChild(Ze);let ra=()=>{if(D()){de.style.width="100%",de.style.maxWidth="100%";let Et=o.launcher?.composerBar??{},Qt=De.dataset.state==="expanded",wa=Et.expandedSize??"anchored";if(!(Qt&&wa!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let as=o.theme?.components?.panel,Aa=Go(o),fr=(Fn,No)=>Fn==null||Fn===""?No:Gt(Aa,Fn)??Fn,Sa="1px solid var(--persona-border)",fl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Oo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=fr(as?.border,Sa),fe.style.borderRadius=fr(as?.borderRadius,Oo),fe.style.boxShadow=fr(as?.shadow,fl),fe.style.overflow="hidden";return}let l=Ht(o),g=o.launcher?.sidebarMode??!1,h=l||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,J=Go(o),N=(Et,Qt)=>Et==null||Et===""?Qt:Gt(J,Et)??Et,G=e.ownerDocument.defaultView??window,ie=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,se=G.innerWidth<=ge,Ce=ie&&se&&k,Ve=l&&ie&&se,ft=o.launcher?.position??"bottom-left",tt=ft==="bottom-left"||ft==="top-left",nn=o.launcher?.zIndex??Vt,Mt="var(--persona-panel-border, 1px solid var(--persona-border))",Rt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",H="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ee=A&&!Ce&&!Ve;Ee?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let _e=Ee?Mt:g||Ce?"none":Mt,Se=Ee?Rt:Ce?"none":g?tt?"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":Rt;l&&!Ce&&!Ee&&(Se="none",_e="none");let At=Ee?H:g||Ce?"0":H,gt=N(L?.border,_e),Ot=N(L?.shadow,Se),mt=N(L?.borderRadius,At),Yt=oa(),It=Yt==="detached",ke=Yt==="welded";e.classList.toggle("persona-artifact-detached-split",It),e.classList.toggle("persona-artifact-welded-split",ke);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"&&Xt(o)&&vc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",wt);let dt=It||wt?"none":Ot,ht=It?Mt:ke?"none":gt,Qe=It?H:mt;wt&&(ht="none",Qe="0");let We=L?.borderRadius!=null&&L.borderRadius!=="",bt=wt&&!We?"0":mt,Ut=ae.scrollTop;e.style.cssText="",De.style.cssText="",de.style.cssText="",fe.style.cssText="",ae.style.cssText="",Y.style.cssText="",ze&&(ae.style.display="none"),(h||x)&&(e.style.minWidth="0");let fn=()=>{if(Ut<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===Ut)return;let Qt=ae.scrollHeight-ae.clientHeight;Qt<=0||(ae.scrollTop=Math.min(Ut,Qt))})};if(Ce){De.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"),De.style.cssText=`
|
|
48
|
+
`,_.addEventListener("click",()=>{g=O,M.forEach((U,z)=>{let Y=z<O;U.classList.toggle("selected",Y),U.setAttribute("aria-checked",z===O-1?"true":"false")})}),M.push(_),S.appendChild(_)}b.appendChild(S);let P=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),O.appendChild(P),b.appendChild(O)}let T=document.createElement("div");T.className="persona-feedback-actions";let L=document.createElement("button");L.type="button",L.className="persona-feedback-btn persona-feedback-btn-skip",L.textContent=i,L.addEventListener("click",()=>{n?.(),c.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let O=P?.value.trim()||void 0;await t(g,O),c.remove()}catch(O){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",O)}}),T.appendChild(L),T.appendChild(H),b.appendChild(T),c.appendChild(b),c}function Td(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let b=null,f=document.createElement("div");f.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,x.appendChild(S),f.appendChild(x);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=c,P.appendChild(T),P.appendChild(L);let H=document.createElement("div");H.className="persona-feedback-numbers";let O=[];for(let A=0;A<=10;A++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${A} out of 10`),G.textContent=String(A),G.dataset.rating=String(A),A<=6?G.classList.add("persona-feedback-detractor"):A<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{b=A,O.forEach((Q,le)=>{Q.classList.toggle("selected",le===A),Q.setAttribute("aria-checked",le===A?"true":"false")})}),O.push(G),H.appendChild(G)}M.appendChild(P),M.appendChild(H),f.appendChild(M);let _=null;if(p){let A=document.createElement("div");A.className="persona-feedback-comment-container",_=document.createElement("textarea"),_.className="persona-feedback-comment",_.placeholder=s,_.rows=3,_.setAttribute("aria-label","Additional comments"),A.appendChild(_),f.appendChild(A)}let U=document.createElement("div");U.className="persona-feedback-actions";let z=document.createElement("button");z.type="button",z.className="persona-feedback-btn persona-feedback-btn-skip",z.textContent=i,z.addEventListener("click",()=>{n?.(),g.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=a,Y.addEventListener("click",async()=>{if(b===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let A=_?.value.trim()||void 0;await t(b,A),g.remove()}catch(A){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",A)}}),U.appendChild(z),U.appendChild(Y),f.appendChild(U),g.appendChild(f),g}var cs="persona-chat-history",iS=30*1e3,lS=641,cS={"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 dS(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=cS[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 ol(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 pS(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 uS(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ed=e=>!e||typeof e!="object"?{}:{...e},Mm=e=>e.map(t=>({...t,streaming:!1})),km=(e,t,n)=>{let o=e?.markdown?_r(e.markdown):null,r=Os(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Zn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Ru(a):a,g=o(c);d=r&&p?r(g):g}else d=eo(a);return d}};function Lm(e){let t=y("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=se(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=y("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var gS=(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},fS=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:gS(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Md=(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=ta(t),r=o.features;o=Xi(o);let s=Qi.getForInstance(o.plugins),a=!1,i=Gf(()=>o),{plugin:p,teardown:d}=rm();o.components&&Fn.registerAll(o.components);let c=Sm(),b=o.persistState===!1?null:o.storageAdapter??xd(),f={},x=null,C=!1,S=l=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:v}=u;return v&&(C=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(b?.load)try{let l=b.load();if(l&&typeof l.then=="function")x=l.then(u=>S(u??{messages:[],metadata:{}}));else{let m=S(l??{messages:[],metadata:{}});m.metadata&&(f=Ed(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=S({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let M=()=>f,P=l=>{f=l({...f})??{},Pl()},T=o.actionParsers&&o.actionParsers.length?o.actionParsers:[el],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ls.message,ls.messageAndClick],H=tl({parsers:T,handlers:L,getSessionMetadata:M,updateSessionMetadata:P,emit:c.emit,documentRef:typeof document<"u"?document:null});H.syncFromMetadata();let O=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,U=o.autoFocusInput??!1,z=_,Y=O,A=o.layout?.header?.layout,G=!1,Q=()=>Wo(o),le=()=>O||Q(),J=Q()?!1:O?_:!0,me=!1,ee=null,ye=()=>{me=!0,ee&&clearTimeout(ee),ee=setTimeout(()=>{me&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),me=!1)},1e4)},Z=km(o,H,ye),ue=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,fe=o.features?.showEventStreamToggle??!1,be=o.features?.scrollToBottom??{},he=o.features?.scrollBehavior??{},rt=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,$e=fe?new ya(rt):null,Ve=o.features?.eventStream?.maxEvents??2e3,Le=fe?new ha(Ve,$e):null,_e=fe?new ba:null,we=null,ae=!1,Re=null,ct=0;$e?.open().then(()=>Le?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let et={onCopy:l=>{c.emit("message:copy",l),F?.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{c.emit("message:feedback",l),F?.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(l)}},vt=o.statusIndicator??{},wn=l=>l==="idle"?vt.idleText??Bt.idle:l==="connecting"?vt.connectingText??Bt.connecting:l==="connected"?vt.connectedText??Bt.connected:l==="error"?vt.errorText??Bt.error:l==="paused"?vt.pausedText??Bt.paused:l==="resuming"?vt.resumingText??Bt.resuming:Bt[l];function An(l,u,m,v){if(v==="idle"&&m.idleLink){l.textContent="";let w=document.createElement("a");w.href=m.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=u,w.style.color="inherit",w.style.textDecoration="none",l.appendChild(w)}else l.textContent=u}let Ze=Kf({config:o,showClose:le()}),{wrapper:ke,panel:ve,pillRoot:tt}=Ze.shell,Te=Ze.panelElements,{container:Ce,body:re,messagesWrapper:Ae,starterSuggestions:Sn,transcriptSuggestions:ne,suggestions:E,textarea:I,sendButton:h,sendButtonWrapper:W,composerForm:R,statusText:B,welcomeHost:V,welcomeIconHolder:$,greetingHost:K,introTitle:de,introSubtitle:Ue,closeButton:pe,iconHolder:Pe,headerTitle:ze,headerSubtitle:je,header:He,footer:Se,actionsRow:nt,rightActions:St}=Te,un=Te.leftActions,wa=Te.setSendButtonMode,oe=Te.micButton,gn=Te.micButtonWrapper,dt=Te.attachmentButton,fn=Te.attachmentButtonWrapper,kt=Te.attachmentInput,Tn=Te.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),re.classList.add("persona-relative");let ph=12,ds=()=>be.label??"",uh=()=>be.iconName??"arrow-down",gh=()=>be.enabled!==!1,nn=()=>he.mode??"anchor-top",ao=()=>nn()==="follow"||nn()==="anchor-top"&&xs,ps=()=>he.anchorTopOffset??16,fh=()=>he.restorePosition??"bottom",Fd=()=>he.pauseOnInteraction===!0,_d=()=>he.showActivityWhilePinned!==!1,$d=()=>he.announce===!0,gl=()=>he.scrollbar??"on-scroll",Rt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Rt.type="button",Rt.style.display="none",Rt.setAttribute("data-persona-scroll-to-bottom","true");let us=y("span","persona-flex persona-items-center"),fl=y("span",""),Oo=y("span","");Oo.setAttribute("data-persona-scroll-to-bottom-count",""),Oo.style.display="none",Rt.append(us,fl,Oo),Ce.appendChild(Rt);let mn=y("div","persona-stream-anchor-spacer");mn.setAttribute("aria-hidden","true"),mn.setAttribute("data-persona-anchor-spacer",""),mn.style.flexShrink="0",mn.style.pointerEvents="none",mn.style.height="0px",mn.style.display="none",re.appendChild(mn);let No=y("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"}),Ce.appendChild(No);let gs=null,Aa=null,jd=l=>{!$d()||!l||(Aa=l,gs===null&&(gs=setTimeout(()=>{gs=null,Aa&&$d()&&(No.textContent=Aa),Aa=null},400)))},Fo=()=>{let u=Se.style.display==="none"?0:Se.offsetHeight;Rt.style.bottom=`${u+ph}px`};Fo();let Ud=()=>{let l=!!ds();Rt.setAttribute("aria-label",ds()||"Jump to latest"),Rt.title=ds(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),us.innerHTML="";let u=se(uh(),"14px","currentColor",2);u?(us.appendChild(u),us.style.display=""):us.style.display="none",fl.textContent=ds(),fl.style.display=l?"":"none"};Ud();let xt=null,Jt=null,zd=null,qd=s.find(l=>l.renderHeader);if(qd?.renderHeader){let l=qd.renderHeader({config:o,defaultRenderer:()=>{let u=Ho({config:o,showClose:le()});return Zr(Ce,u,o),u.header},onClose:()=>pt(!1,"user")});if(l){let u=Ce.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),He=l,Ze.header.element=l)}}let ml=()=>{if(!Le)return;if(ae=!0,!we&&Le&&(we=lm({buffer:Le,getFullHistory:()=>Le.getAllFromStore(),onClose:()=>fs(),config:o,plugins:s,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),we&&(re.style.display="none",Se.parentNode?.insertBefore(we.element,Se),we.update()),Xe){Xe.style.boxShadow=`inset 0 0 0 1.5px ${Gt.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&Xe.classList.add(m))}let l=()=>{if(!ae)return;let u=Date.now();u-ct>=200&&(we?.update(),ct=u),Re=requestAnimationFrame(l)};ct=0,Re=requestAnimationFrame(l),jt(),c.emit("eventStream:opened",{timestamp:Date.now()})},fs=()=>{if(ae){if(ae=!1,we&&we.element.remove(),re.style.display="",Xe){Xe.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(u=>u&&Xe.classList.remove(u))}Re!==null&&(cancelAnimationFrame(Re),Re=null),jt(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Xe=null;if(fe){let l=o.features?.eventStream?.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");Xe=y("button",u),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=Gt.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let m=se("activity","18px","currentColor",1.5);m&&Xe.appendChild(m);let v=Te.clearChatButtonWrapper,w=Te.closeButtonWrapper,k=v||w;k&&k.parentNode===He?He.insertBefore(Xe,k):He.appendChild(Xe),Xe.addEventListener("click",()=>{ae?fs():ml()})}let Vd=l=>{let u=o.attachments;if(!u?.enabled)return;let m=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!m){m=y("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 w=l.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(m,w):l.insertBefore(m,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let w=y("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(u.allowedTypes??no).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),l.appendChild(w)}},hl=s.find(l=>l.renderComposer),yl=!1,Kd=l=>{if(!hl?.renderComposer)return null;let u=o.composer,m=a?F.isStreaming():!1;return hl.renderComposer({config:o,defaultRenderer:l,requestRender:()=>py(),storage:i(hl.id),onSubmit:v=>{if(!F||F.isStreaming())return;let w=v.trim(),k=xt?.hasAttachments()??!1;if(!w&&!k)return;Gp();let j;k&&(j=[],j.push(...xt.getContentParts()),w&&j.push(lr(w))),F.sendMessage(w,{contentParts:j}),k&&xt.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{kt?.click()},models:u?.models,selectedModelId:u?.selectedModelId,onModelChange:v=>{o.composer={...o.composer,selectedModelId:v},o.agent&&(o.agent={...o.agent,model:v})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{zd?.()}:void 0})},Gd=Kd(()=>es({config:o}).footer);Gd&&(Ze.replaceComposer(Gd),Se=Ze.composer.footer,yl=!0);let Jd=l=>{let u=(...ge)=>{for(let ce of ge){let xe=l.querySelector(ce);if(xe)return xe}return null},m=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),w=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),j=l.querySelector("[data-persona-composer-status]");m&&(R=m),v&&(I=v),w&&(h=w),k&&(oe=k,gn=k.parentElement),j&&(B=j);let N=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(E=N);let q=u("[data-persona-composer-attachment-button]",".persona-attachment-button");q&&(dt=q,fn=q.parentElement),kt=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Tn=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let X=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");X&&(nt=X),un=u(".persona-widget-composer__left-actions")};Vd(Se),Jd(Se);let ms=Eo(o,Q());ms&&(Ae.style.maxWidth=ms,Ae.style.marginLeft="auto",Ae.style.marginRight="auto",Ae.style.width="100%",K.style.maxWidth=ms,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",Sn.style.maxWidth=ms,ne.style.maxWidth=ms,ne.style.marginLeft="auto",ne.style.marginRight="auto",ne.style.width="100%");let Yd=()=>{let l=Eo(o,Q());if(!(!l||Q()))for(let u of[R,E,Tn,B])u&&(u.style.maxWidth=l,u.style.marginLeft="auto",u.style.marginRight="auto")};Yd();let Xd=()=>{!o.attachments?.enabled||!kt||!Tn||(xt?xt.remountPreviews(Tn):(xt=Kr.fromConfig(o.attachments),xt.setPreviewsContainer(Tn)),kt.addEventListener("change",l=>{let u=l.target;xt?.handleFileSelect(u.files),u.value=""}),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(Lm(o.attachments.dropOverlay)))};Xd();let mh=()=>Jt?.prefetch(),Qd=()=>{if(!(!o.contextMentions?.enabled||!I)&&(Jt=Dg({config:o,textarea:I,anchor:R??I,getMessages:()=>F.getMessages(),liveRegionHost:Ce}),Jt)){let l=I;l.parentElement?.insertBefore(Jt.contextRow,l);let u=Jt.affordanceButtons;for(let m=u.length-1;m>=0;m--){let v=u[m];un?un.insertBefore(v,un.firstChild):R?.appendChild(v)}}};Qd(),(()=>{let l=o.layout?.slots??{},u=v=>{switch(v){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return Ae;case"footer-top":return E;case"composer":return R;case"footer-bottom":return B;default:return null}},m=(v,w)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")He.insertBefore(w,He.firstChild);else if(v==="header-right")He.appendChild(w);else{let k=He.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):He.appendChild(w)}break;case"body-top":{let k=re.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):re.insertBefore(w,re.firstChild);break}case"body-bottom":re.appendChild(w);break;case"footer-top":E.replaceWith(w);break;case"footer-bottom":B.replaceWith(w);break;default:break}};for(let[v,w]of Object.entries(l))if(w)try{let k=w({config:o,defaultContent:()=>u(v)});k&&m(v,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,k)}})();let Zd=l=>{let m=l.target.closest('button[data-expand-header="true"]');if(!m)return;let v=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let w=v.getAttribute("data-message-id");if(!w)return;let k=m.getAttribute("data-bubble-type");if(k==="reasoning")os.has(w)?os.delete(w):os.add(w),Jf(w,v);else if(k==="tool")rs.has(w)?rs.delete(w):rs.add(w),Yf(w,v,o);else if(k==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=yr.get(w)??N;yr.set(w,!q),em(w,v,o)}Vo.delete(w)};Ae.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zd(l))}),Ae.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zd(l))}),Ae.addEventListener("copy",l=>{let{clipboardData:u}=l;if(!u)return;let m=Ae.getRootNode(),v=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let w=v.toString(),k=df(w);!k||k===w||(u.setData("text/plain",k),l.preventDefault())});let bl=new Map,ep=null,tp="idle",hh={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},yh=(l,u)=>{let{icon:m,label:v}=hh[u];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let w=se(m,14,"currentColor",2);w&&(l.innerHTML="",l.appendChild(w))},np=()=>{Ae.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let v=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;yh(u,v&&v===ep?tp:"idle")})};Ae.addEventListener("click",l=>{let m=l.target.closest(".persona-message-action-btn[data-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.closest("[data-actions-for]");if(!v)return;let w=v.getAttribute("data-actions-for");if(!w)return;let k=m.getAttribute("data-action");if(k==="copy"){let N=F.getMessages().find(q=>q.id===w);if(N&&et.onCopy){let q=N.content||"";navigator.clipboard.writeText(q).then(()=>{m.classList.add("persona-message-action-success");let X=se("check",14,"currentColor",2);X&&(m.innerHTML="",m.appendChild(X)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let ge=se("copy",14,"currentColor",2);ge&&(m.innerHTML="",m.appendChild(ge))},2e3)}).catch(X=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",X)}),et.onCopy(N)}}else if(k==="read-aloud")F.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let N=(bl.get(w)??null)===k,q=k==="upvote"?"thumbs-up":"thumbs-down";if(N){bl.delete(w),m.classList.remove("persona-message-action-active");let X=se(q,14,"currentColor",2);X&&(m.innerHTML="",m.appendChild(X))}else{let X=k==="upvote"?"downvote":"upvote",ge=v.querySelector(`[data-action="${X}"]`);if(ge){ge.classList.remove("persona-message-action-active");let ut=se(X==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(ge.innerHTML="",ge.appendChild(ut))}bl.set(w,k),m.classList.add("persona-message-action-active");let ce=se(q,14,"currentColor",2);ce&&(ce.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(ce)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ge=F.getMessages().find(yt=>yt.id===w);Ge&&et.onFeedback&&et.onFeedback({type:k,messageId:Ge.id,message:Ge})}}}),Ae.addEventListener("click",l=>{let m=l.target.closest("button[data-approval-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.closest(".persona-approval-bubble");if(!v)return;let w=v.getAttribute("data-message-id");if(!w)return;let k=m.getAttribute("data-approval-action");if(!k)return;let j=k==="approve"?"approved":"denied",q=F.getMessages().find(ge=>ge.id===w);if(!q?.approval)return;let X=v.querySelector("[data-approval-buttons]");X&&X.querySelectorAll("button").forEach(ce=>{ce.disabled=!0,ce.style.opacity="0.5",ce.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?F.resolveWebMcpApproval(w,j):F.resolveApproval(q.approval,j)});let Je=null,hs=null,_o=()=>{},ys="none",Sa=null,En={artifacts:[],selectedId:null},Un=!1,Mn=!1,bs=!1,wr=!1,op=()=>wr||En.artifacts.some(l=>to(o.features?.artifacts,l)==="panel"),Ta=()=>En.artifacts.length>0&&!Un&&op(),at={current:null},vl=(l,u)=>{let m=F.getArtifactById(u),v=m?.markdown,w=m?.title||"artifact",k=m?.file,j=m?.artifactType??"markdown";if(!v){let X=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(X){let ce=F.getMessages().find(xe=>xe.id===X);if(ce?.rawContent)try{let xe=JSON.parse(ce.rawContent);v=xe?.props?.markdown,w=xe?.props?.title||w,xe?.props?.file&&typeof xe.props.file=="object"&&(k=xe.props.file),!m&&typeof xe?.props?.artifactType=="string"&&(j=xe.props.artifactType)}catch{}}}return{markdown:v,title:w,file:k,artifactType:j}};Ae.addEventListener("click",l=>{let m=l.target.closest("[data-download-artifact]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:k,title:j,file:N}=vl(m,v);if(!k)return;let{filename:q,mime:X,content:ge}=Vg({title:j,markdown:k,file:N}),ce=new Blob([ge],{type:X}),xe=URL.createObjectURL(ce),Ge=document.createElement("a");Ge.href=xe,Ge.download=q,Ge.click(),URL.revokeObjectURL(xe)}),Ae.addEventListener("click",l=>{let m=l.target.closest("[data-artifact-custom-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-artifact-custom-action");if(!v)return;let w=m.closest("[data-artifact-inline]"),k=w?null:m.closest("[data-open-artifact]"),j=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,q=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(yt=>yt.id===v);if(!q)return;let{markdown:X,title:ge,file:ce,artifactType:xe}=vl(m,j??""),Ge={artifactId:j,title:ge,artifactType:xe,markdown:X,file:ce};try{Promise.resolve(q.onClick(Ge)).catch(()=>{})}catch{}}),Ae.addEventListener("click",l=>{let m=l.target.closest("[data-copy-artifact]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-copy-artifact");if(!v)return;let w=F.getArtifactById(v),k="";if(w)k=sa(w);else{let{markdown:j,file:N,artifactType:q}=vl(m,v);q==="markdown"&&(k=sa({id:v,artifactType:"markdown",status:"complete",markdown:j??"",...N?{file:N}:{}}))}k&&navigator.clipboard.writeText(k).then(()=>{let j=se("check",16,"currentColor",2);j&&(m.replaceChildren(j),setTimeout(()=>{let N=se("copy",16,"currentColor",2);N&&m.replaceChildren(N)},1500))}).catch(()=>{})}),Ae.addEventListener("click",l=>{let m=l.target.closest("[data-expand-artifact-inline]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Un=!1,wr=!0,Mn=!0,bs=!0,F.selectArtifact(v),zn())}),Ae.addEventListener("click",l=>{let u=l.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let v=m.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(l.preventDefault(),l.stopPropagation(),Un=!1,wr=!0,F.selectArtifact(v),zn())}),Ae.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),u.click())});let Ar=Te.composerOverlay,Sr=(l,u,m)=>{let v=u.trim();if(!v||!at.current)return;let w=l.getAttribute("data-tool-call-id")??"",k=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:w,answer:v,answers:m.structured,values:m.values??(m.source==="multi"?v.split(", "):[v]),isFreeText:k,source:m.source},bubbles:!0,composed:!0})),ar(Ar,w);let j=at.current.getMessages().find(N=>N.toolCall?.id===w);j?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(j,m.structured??v):at.current.sendMessage(v)},$o=l=>{let u=at.current;if(!u)return;let m=l.getAttribute("data-tool-call-id")??"",v=u.getMessages().find(w=>w.toolCall?.id===m);v&&u.persistAskUserQuestionProgress(v,{answers:ni(l,v),currentIndex:vn(l)})},rp=l=>Object.entries(l).map(([u,m])=>`${u}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),xl=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let u=vn(l),m=jr(l);if(u>=m-1)return;let v=at.current?.getMessages().find(w=>w.toolCall?.id===l.getAttribute("data-tool-call-id"));v&&(oi(l,v,o,u+1),$o(l))};Ar.addEventListener("click",l=>{let m=l.target.closest("[data-ask-user-action]");if(!m)return;let v=m.closest("[data-persona-ask-sheet-for]");if(!v)return;let w=m.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),w==="dismiss"){let k=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),ar(Ar,k);let j=at.current?.getMessages().find(N=>N.toolCall?.id===k);j?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(j),at.current?.resolveAskUserQuestion(j,"(dismissed)"));return}if(w==="pick"){let k=m.getAttribute("data-option-label");if(!k)return;let j=v.getAttribute("data-multi-select")==="true",N=Co(v);if(N&&j){let q=sr(v)[vn(v)],X=new Set(Array.isArray(q)?q:[]);X.has(k)?X.delete(k):X.add(k),wo(v,Array.from(X)),$o(v);return}if(N){wo(v,k),$o(v),xl(v);return}if(j){let q=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",q?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!q);let X=v.querySelector('[data-ask-user-action="submit-multi"]');X&&(X.disabled=uc(v).length===0);return}Sr(v,k,{source:"pick",values:[k]});return}if(w==="submit-multi"){let k=uc(v);if(k.length===0)return;Sr(v,k.join(", "),{source:"multi",values:k});return}if(w==="open-free-text"){let k=v.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(w==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(w==="submit-free-text"){let j=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!j.trim())return;if(Co(v)){wo(v,j.trim()),$o(v),xl(v);return}Sr(v,j,{source:"free-text"});return}if(w==="next"||w==="back"){if(!at.current)return;let k=v.getAttribute("data-tool-call-id")??"",j=at.current.getMessages().find(ce=>ce.toolCall?.id===k);if(!j)return;let q=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let ce=sr(v)[vn(v)];(typeof ce!="string"||ce!==q)&&wo(v,q)}let X=w==="next"?1:-1,ge=vn(v)+X;oi(v,j,o,ge),$o(v);return}if(w==="submit-all"){if(!at.current)return;let k=v.getAttribute("data-tool-call-id")??"",j=at.current.getMessages().find(ce=>ce.toolCall?.id===k);if(!j)return;let q=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&wo(v,q);let X=ni(v,j);at.current.persistAskUserQuestionProgress(j,{answers:X,currentIndex:vn(v)});let ge=rp(X);Sr(v,ge||"(submitted)",{source:"submit-all",structured:X});return}if(w==="skip"){if(!at.current)return;let k=v.getAttribute("data-tool-call-id")??"",j=at.current.getMessages().find(xe=>xe.toolCall?.id===k);if(!j)return;let N=Co(v),q=vn(v),X=jr(v),ge=q>=X-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),ar(Ar,k),j.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(j),at.current.resolveAskUserQuestion(j,"(dismissed)"));return}wo(v,"");let ce=v.querySelector('[data-ask-free-text-input="true"]');if(ce&&(ce.value=""),ge){let xe=ni(v,j),Ge=rp(xe);Sr(v,Ge||"(skipped)",{source:"submit-all",structured:xe});return}oi(v,j,o,q+1),$o(v);return}}),Ar.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let m=l.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let v=m.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let w=m.value;if(w.trim()){if(Co(v)){wo(v,w.trim()),$o(v),xl(v);return}Sr(v,w,{source:"free-text"})}});let sp=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=Ar.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),k=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];k&&(l.preventDefault(),k.click())};document.addEventListener("keydown",sp);let io=null,Ct=null,vs=null,Ea=null,Cl=()=>{},ap=!1,Ma="",ka="";function wl(){Ea?.(),Ea=null}let ip=()=>{if(!io||!Ct)return;let l=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||m){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 v=io.firstElementChild;if(!v||v===Ct)return;let w=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${w}px`,Ct.style.zIndex="5";let k=hd(io,u),j=v.offsetWidth+k/2-w/2;Ct.style.left=`${Math.max(0,j)}px`},La=()=>{},bh=()=>{let l=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||l.innerWidth>m?!1:O||Mt(o)},Pa=()=>!Qt(o)||!Ta()||e.classList.contains("persona-artifact-narrow-host")||bh()||(e.ownerDocument.defaultView??window).innerWidth<lS?"none":fd(o)?"detached":"welded",zn=()=>{if(!Je||!Qt(o))return;va(e,o),xa(e,o),La();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=ve.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l);let m=Ta();Je.setVisible(m),Je.update(En),Un?(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),Mn=!1,bs=!1):En.artifacts.length>0&&op()?(Je.element.classList.remove("persona-hidden"),Je.setMobileOpen(!0)):(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),Mn=!1,bs=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Je.setExpandToggleVisible(v),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),!v&&!bs&&(Mn=!1),Mn!==ap){let k=Je.element;Mn?(Ma=k.style.width,ka=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Ma&&(k.style.width=Ma),ka&&(k.style.maxWidth=ka),Ma="",ka=""),ap=Mn}e.classList.toggle("persona-artifact-expanded",Mn),Je.setExpanded(Mn);let w=Pa();w!==ys&&(ys=w,_o()),Cl()};if(Qt(o)){ve.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Ce),Je=cm(o,{onSelect:m=>at.current?.selectArtifact(m),onDismiss:()=>{Un=!0,zn()},onToggleExpand:()=>{let m=!Mn,v=En.selectedId??En.artifacts[En.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:m})!==!0&&(Mn=m,m||(bs=!1),zn())}}),Je.element.classList.add("persona-hidden"),io=u,u.appendChild(l),u.appendChild(Je.element),Je.backdrop&&ve.appendChild(Je.backdrop),ve.appendChild(u),Cl=()=>{if(!io||!Je)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){vs?.(),vs=null,wl(),Ct&&(Ct.remove(),Ct=null),Je.element.style.removeProperty("width"),Je.element.style.removeProperty("maxWidth");return}if(!Ct){let v=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let w=e.ownerDocument,k=w.defaultView??window,j=N=>{if(!Je||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||k.innerWidth<=640)return;N.preventDefault(),wl();let q=N.clientX,X=Je.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,ce=Ge=>{let yt=io.getBoundingClientRect().width,ut=e.classList.contains("persona-artifact-welded-split"),sn=hd(io,k),Et=ut?0:v.getBoundingClientRect().width||6,Wt=X-(Ge.clientX-q),D=xm(Wt,yt,sn,Et,ge?.resizableMinWidth,ge?.resizableMaxWidth);Je.element.style.width=`${D}px`,Je.element.style.maxWidth="none",ip()},xe=()=>{w.removeEventListener("pointermove",ce),w.removeEventListener("pointerup",xe),w.removeEventListener("pointercancel",xe),Ea=null;try{v.releasePointerCapture(N.pointerId)}catch{}};Ea=xe,w.addEventListener("pointermove",ce),w.addEventListener("pointerup",xe),w.addEventListener("pointercancel",xe);try{v.setPointerCapture(N.pointerId)}catch{}};v.addEventListener("pointerdown",j),Ct=v,io.insertBefore(v,Je.element),vs=()=>{v.removeEventListener("pointerdown",j)}}if(Ct){let v=Ta();Ct.classList.toggle("persona-hidden",!v),ip()}},La=()=>{if(!O||!Je||(o.launcher?.sidebarMode??!1)||Mt(o)&&cn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&v.innerWidth<=k||!um(o,O))return;let j=o.launcher?.width??o.launcherWidth??xn,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ta()?(ve.style.width=N,ve.style.maxWidth=N):(ve.style.width=j,ve.style.maxWidth=j)},typeof ResizeObserver<"u"&&(hs=new ResizeObserver(()=>{zn()}),hs.observe(ve))}else ve.appendChild(Ce);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(Se)),e.appendChild(ke),tt&&e.appendChild(tt);let Al=()=>{if(Q()){ve.style.width="100%",ve.style.maxWidth="100%";let Pt=o.launcher?.composerBar??{},tn=ke.dataset.state==="expanded",Ga=Pt.expandedSize??"anchored";if(!(tn&&Ga!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let Hs=o.theme?.components?.panel,Ja=ur(o),Dr=(Xn,nr)=>Xn==null||Xn===""?nr:Xt(Ja,Xn)??Xn,Ya="1px solid var(--persona-border)",nc="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",tr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=Dr(Hs?.border,Ya),Ce.style.borderRadius=Dr(Hs?.borderRadius,tr),Ce.style.boxShadow=Dr(Hs?.shadow,nc),Ce.style.overflow="hidden";return}let l=Mt(o),u=o.launcher?.sidebarMode??!1,m=l||u||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,w=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,j=ur(o),N=(Pt,tn)=>Pt==null||Pt===""?tn:Xt(j,Pt)??Pt,q=e.ownerDocument.defaultView??window,X=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,ce=q.innerWidth<=ge,xe=X&&ce&&O,Ge=l&&X&&ce,yt=o.launcher?.position??"bottom-left",ut=yt==="bottom-left"||yt==="top-left",sn=o.launcher?.zIndex??_t,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)))",D="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=w&&!xe&&!Ge;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ne=Ie?Et:u||xe?"none":Et,Ee=Ie?Wt:xe?"none":u?ut?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":v?"none":Wt;l&&!xe&&!Ie&&(Ee="none",Ne="none");let Tt=Ie?D:u||xe?"0":D,gt=N(k?.border,Ne),Nt=N(k?.shadow,Ee),ft=N(k?.borderRadius,Tt),en=Pa(),Ht=en==="detached",We=en==="welded";e.classList.toggle("persona-artifact-detached-split",Ht),e.classList.toggle("persona-artifact-welded-split",We);let Fe="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",At=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Qt(o)&&fd(o)&&v&&!l;e.classList.toggle("persona-artifact-chat-flush",At);let it=Ht||At?"none":Nt,mt=Ht?Et:We?"none":gt,Ye=Ht?D:ft;At&&(mt="none",Ye="0");let De=k?.borderRadius!=null&&k.borderRadius!=="",bt=At&&!De?"0":ft,qt=re.scrollTop;e.style.cssText="",ke.style.cssText="",ve.style.cssText="",Ce.style.cssText="",re.style.cssText="",Se.style.cssText="",ae&&(re.style.display="none"),(m||v)&&(e.style.minWidth="0");let bn=()=>{if(qt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===qt)return;let tn=re.scrollHeight-re.clientHeight;tn<=0||(re.scrollTop=Math.min(qt,tn))})};if(xe){ke.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ke.style.cssText=`
|
|
49
49
|
position: fixed !important;
|
|
50
50
|
inset: 0 !important;
|
|
51
51
|
width: 100% !important;
|
|
@@ -55,9 +55,9 @@ _Details: ${n.message}_`:o}var As=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: ${sn} !important;
|
|
59
59
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
60
|
-
`,
|
|
60
|
+
`,ve.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 As=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
|
+
`,Ce.style.cssText=`
|
|
74
74
|
display: flex !important;
|
|
75
75
|
flex-direction: column !important;
|
|
76
76
|
flex: 1 1 0% !important;
|
|
@@ -81,33 +81,33 @@ _Details: ${n.message}_`:o}var As=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
|
+
`,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Se.style.flexShrink="0",G=!0,bn();return}let Ka=o?.launcher?.width??o?.launcherWidth??xn;if(!u&&!l)v&&m?(ve.style.width="100%",ve.style.maxWidth="100%"):(ve.style.width=Ka,ve.style.maxWidth=Ka);else if(l)if(cn(o).reveal==="emerge"&&!w){let tn=cn(o).width;ve.style.width=tn,ve.style.maxWidth=tn}else ve.style.width="100%",ve.style.maxWidth="100%";if(La(),ve.style.boxShadow=it,ve.style.borderRadius=bt,Ht?ve.style.border="none":We&&(ve.style.border=gt),Ce.style.border=mt,Ce.style.borderRadius=Ye,Ce.style.boxShadow=Ht&&!At?Fe:"",At&&(Ce.style.background="transparent",re.style.background="transparent",Se.style.background="transparent",Se.style.borderTop="none"),We){let Pt=o.features?.artifacts?.layout;Sa=Pt?.unifiedSplitOuterRadius?.trim()||Pt?.paneBorderRadius?.trim()||ft}else Sa=null;if(l&&!xe&&!Ie&&!Ht&&!We&&k?.border===void 0&&(Ce.style.border="none",cn(o).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.style.borderRight="1px solid var(--persona-border)"),l&&!xe&&We&&k?.border===void 0&&(cn(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.maxHeight="100%",ke.style.height="100%",v&&(ke.style.overflow="hidden"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.height="100%",Ht||(ve.style.overflow="hidden"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Se.style.flexShrink="0"),v&&(Ie||Ht||At)&&!l&&(At||(ke.style.padding="var(--persona-panel-inset)"),ke.style.background="var(--persona-panel-canvas-bg)"),ke.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!v&&!l&&(dn[yt]??dn["bottom-right"]).split(" ").forEach(tn=>ke.classList.add(tn)),u){let Pt=o.launcher?.sidebarWidth??"420px";w?ke.style.cssText=`
|
|
85
85
|
position: fixed !important;
|
|
86
86
|
top: var(--persona-panel-inset) !important;
|
|
87
87
|
bottom: var(--persona-panel-inset) !important;
|
|
88
|
-
width: ${
|
|
88
|
+
width: ${Pt} !important;
|
|
89
89
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
90
90
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
91
91
|
margin: 0 !important;
|
|
92
92
|
padding: 0 !important;
|
|
93
93
|
display: flex !important;
|
|
94
94
|
flex-direction: column !important;
|
|
95
|
-
z-index: ${
|
|
96
|
-
${
|
|
97
|
-
`:
|
|
95
|
+
z-index: ${sn} !important;
|
|
96
|
+
${ut?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
97
|
+
`:ke.style.cssText=`
|
|
98
98
|
position: fixed !important;
|
|
99
99
|
top: 0 !important;
|
|
100
100
|
bottom: 0 !important;
|
|
101
|
-
width: ${
|
|
101
|
+
width: ${Pt} !important;
|
|
102
102
|
height: 100vh !important;
|
|
103
103
|
max-height: 100vh !important;
|
|
104
104
|
margin: 0 !important;
|
|
105
105
|
padding: 0 !important;
|
|
106
106
|
display: flex !important;
|
|
107
107
|
flex-direction: column !important;
|
|
108
|
-
z-index: ${
|
|
109
|
-
${
|
|
110
|
-
`,
|
|
108
|
+
z-index: ${sn} !important;
|
|
109
|
+
${ut?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
110
|
+
`,ve.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 As=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: ${
|
|
121
|
+
box-shadow: ${it} !important;
|
|
122
122
|
border-radius: ${bt} !important;
|
|
123
|
-
${
|
|
124
|
-
`,
|
|
123
|
+
${Ht?"border: none !important;":We?`border: ${gt} !important;`:""}
|
|
124
|
+
`,ve.style.setProperty("width","100%","important"),ve.style.setProperty("max-width","100%","important"),Ce.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 As=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
|
-
${
|
|
136
|
-
${
|
|
137
|
-
`,
|
|
133
|
+
border-radius: ${Ye} !important;
|
|
134
|
+
border: ${mt} !important;
|
|
135
|
+
${Ht&&!At?`box-shadow: ${Fe} !important;`:""}
|
|
136
|
+
${At?"background: transparent !important;":""}
|
|
137
|
+
`,Se.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 Et="max-height: -moz-available !important; max-height: stretch !important;",Qt=g?"":"padding-top: 1.25em !important;",wa=g?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;De.style.cssText+=Et+Qt+wa}fn()};ra(),Ar(e,o),qs(e,o),Vs(e,o),$r=()=>{ra(),Ar(e,o),qs(e,o),Vs(e,o),Ys?e.style.setProperty("--persona-artifact-welded-outer-radius",Ys):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",sd)}),qe.push(()=>{Nr!==null&&clearTimeout(Nr)});let Sn=null,Tn=null;qe.push(()=>{Sn?.(),Sn=null,Tn?.(),Tn=null}),_r&&qe.push(()=>{_r?.disconnect(),_r=null}),qe.push(()=>{zr?.(),zr=null,qi(),xt&&(xt.remove(),xt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),ce&&qe.push(()=>{Te!==null&&(cancelAnimationFrame(Te),Te=null),Oe?.destroy(),Oe=null,Me?.destroy(),Me=null,Ae=null});let ko=null,ld=()=>{ko&&(ko(),ko=null),o.colorScheme==="auto"&&(ko=ks(()=>{Ar(e,o)}))};ld(),qe.push(()=>{ko&&(ko(),ko=null)}),qe.push(i);let sa=o.features?.streamAnimation;if(sa?.type&&sa.type!=="none"){let l=Er(sa.type,sa.plugins);l&&(ci(l,e),qe.push(()=>rf(e)))}let aa=Lf(it),Po=null,_,Vi=l=>{if(!_)return;let g=l??_.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?Ml(g):null;h?aa.render(h,_,ue,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?aa.render([],_,ue,g):aa.render(o.suggestionChips,_,ue,g,o.suggestionChipsConfig)},bn=!1,Lo=Gu(),ar=new Map,Ro=new Map,Qn=new Map,Ki=0,zg=$n()!==null,en=oi(),cn=0,Zn=null,dn=!1,ia=!1,eo=0,vn=null,Io=null,Gi=!1,la=!1,qr=null,Vr=!0,ca=!1,da=null,pa=!1,Wo=()=>{pa=!0},Ji=null,qg=4,ua=24,Vg=80,Xi=new Map,Je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cd=o.voiceRecognition?.autoResume??!1,Dn=l=>{d.emit("voice:state",{active:Je.active,source:l,timestamp:Date.now()})},xn=()=>{E(l=>({...l,voiceState:{active:Je.active,timestamp:Date.now(),manuallyDeactivated:Je.manuallyDeactivated}}))},Kg=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=Rc(u.voiceState),g=!!l.active,h=Number(l.timestamp??0);Je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-h<ZC&&setTimeout(()=>{Je.active||(Je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Je.active=_.isVoiceActive(),Dn("restore"),_.isVoiceActive()&&pr()}):ya("restore"))},1e3)},Gg=()=>_?Zf(_.getMessages()).filter(l=>!l.__skipPersist):[],fa=null,dd=(l,g)=>{typeof console<"u"&&console.error(l,g)},Yi=(l,g)=>{let h=()=>{try{let J=l();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(N=>{dd(g,N)})}catch(J){return dd(g,J),null}},x=fa,A=x?x.then(()=>h()??void 0):h();if(!A)return;let L=A.finally(()=>{fa===L&&(fa=null)});fa=L};function Qi(l){if(!c?.save)return;let h={messages:l?Zf(l):_?Gg():[],metadata:u,artifacts:hn.artifacts,selectedArtifactId:hn.selectedId};Yi(()=>c.save(h),"[AgentWidget] Failed to persist state:")}let ir=null,pd=()=>De.querySelector("#persona-scroll-container")||ae,Kr=()=>{ir!==null&&(cancelAnimationFrame(ir),ir=null),dn=!1},ud=()=>{Zn!==null&&(cancelAnimationFrame(Zn),Zn=null),ia=!1,Kr()},Jg=()=>bn&&el()&&(ln()!=="anchor-top"||Vc()),Zi=()=>{let l=So()||"Jump to latest",g=Jg();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),eo>0?(To.textContent=String(eo),To.style.display="",Pt.setAttribute("aria-label",`${l} (${eo} new)`)):(To.textContent="",To.style.display="none",Pt.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},fd=()=>{eo!==0&&(eo=0,Zi())},el=()=>Gn()?!en.isFollowing():!vo(ae,ua),tn=()=>{if(!Js()||ze){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==fe&&fe.appendChild(Pt),nr();let g=Rn(ae)>0&&el();g?Zi():fd(),Pt.style.display=g?"":"none"},Gr=()=>{en.pause()&&(ud(),tn())},to=()=>{en.resume(),fd(),tn()},no=(l=!1)=>{Gn()&&en.isFollowing()&&(!l&&!bn||(Zn!==null&&(cancelAnimationFrame(Zn),Zn=null),ia=!0,Zn=requestAnimationFrame(()=>{Zn=null,ia=!1,en.isFollowing()&&Xg(pd(),l?220:140)})))},gd=(l,g,h,x=()=>!0)=>{let A=l.scrollTop,L=g(),J=L-A;if(Kr(),Math.abs(J)<1){dn=!0,l.scrollTop=L,cn=l.scrollTop,dn=!1;return}let N=performance.now();dn=!0;let G=ge=>1-Math.pow(1-ge,3),ie=ge=>{if(!x()){Kr();return}let se=g();se!==L&&(L=se,J=L-A);let Ce=ge-N,Ve=Math.min(Ce/h,1),ft=G(Ve),tt=A+J*ft;l.scrollTop=tt,cn=l.scrollTop,Ve<1?ir=requestAnimationFrame(ie):(l.scrollTop=L,cn=l.scrollTop,ir=null,dn=!1)};ir=requestAnimationFrame(ie)},Xg=(l,g=500)=>{let h=Rn(l)-l.scrollTop;if(Math.abs(h)<1){cn=l.scrollTop;return}if(Math.abs(h)>=Vg){Kr(),dn=!0,l.scrollTop=Rn(l),cn=l.scrollTop,dn=!1;return}gd(l,()=>Rn(l),g,()=>en.isFollowing())},md=()=>{let l=pd();dn=!0,l.scrollTop=Rn(l),cn=l.scrollTop,dn=!1,tn()},hd=l=>{let g=0,h=l;for(;h&&h!==ae;)g+=h.offsetTop,h=h.offsetParent;return g},Yg=()=>{let l=ae.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??ae.ownerDocument.getSelection()},ga=()=>Zu(Yg(),ae),yd=()=>{if(Og()!=="last-user-turn")return!1;let l=_?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(L=>L.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=ae.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,hd(x)-zc()),Rn(ae));return dn=!0,ae.scrollTop=A,cn=ae.scrollTop,dn=!1,ln()==="follow"&&!vo(ae,ua)&&en.pause(),tn(),!0},bd=l=>{Jn.style.height=`${Math.max(0,Math.round(l))}px`,vn&&(vn.spacerHeight=Math.max(0,l))},Jr=()=>{Io!==null&&(cancelAnimationFrame(Io),Io=null),Kr(),vn=null,Jn.style.height="0px"},vd=l=>{Io!==null&&cancelAnimationFrame(Io),Io=requestAnimationFrame(()=>{Io=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ae.querySelector(`[data-message-id="${g}"]`);if(!h)return;let x=hd(h),A=vn?.spacerHeight??0,L=ae.scrollHeight-A,{targetScrollTop:J,spacerHeight:N}=ef({anchorOffsetTop:x,topOffset:zc(),viewportHeight:ae.clientHeight,contentHeight:L});vn={initialSpacerHeight:N,contentHeightAtAnchor:L,spacerHeight:N},bd(N),gd(ae,()=>J,220)})},Qg=()=>{if(Gn()){if(!en.isFollowing()||vo(ae,1))return;no(!bn);return}if(vn&&vn.initialSpacerHeight>0){let l=ae.scrollHeight-vn.spacerHeight,g=tf({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:l});g!==vn.spacerHeight&&bd(g)}tn()},Zg=l=>{let g=ln();g==="follow"?(to(),no(!0)):g==="anchor-top"&&(Vr=!1,ca=!0,pa=!1,da=l,vd(l))},em=()=>{if(ln()==="anchor-top"){if(ca){Vr=!1;return}Vr=!0,Jr(),to(),no(!0)}},tm=l=>{if(ln()!=="anchor-top"||!ca||pa||ga())return;let g=qr===null;for(let h of l){if(!g){h.id===qr&&(g=!0);continue}if(Qu(h)){if(h.id===da)return;da=h.id,vd(h.id);return}}},nm=l=>{let g=new Map;l.forEach(h=>{let x=Xi.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(d.emit("assistant:message",h),!la&&(ln()!=="anchor-top"||Vc())&&el()&&(eo+=1,Zi(),tn(),Gc(eo===1?"1 new message below.":`${eo} 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}))}),Xi.clear(),g.forEach((h,x)=>{Xi.set(x,h)})},ma=(l,g)=>{let h=g==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",L=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",L)},Ho=(l,g)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${l}`,h.setAttribute("data-wrapper-id",l),ma(h,g),h},om=(l,g,h)=>{let x=document.createElement("div"),L=(()=>{let H=s.find(Ee=>Ee.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(H,Ee)=>Ee==null?!1:typeof Ee=="string"?(H.textContent=Ee,!0):(H.appendChild(Ee),!0),N=new Set,G=new Map,ie=new Set,ge=s.some(H=>H.renderAskUserQuestion),se=[],Ce=[],Ve=o.enableComponentStreaming!==!1,ft=o.approval!==!1,tt=[];if(g.forEach(H=>{N.add(H.id),G.set(H.id,H.role);let Ee=ge&&io(H),_e=ft&&H.variant==="approval"&&!!H.approval,Se=!Ee&&H.role==="assistant"&&!H.variant&&Ve&&ki(H);!_e&&Qn.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),Qn.delete(H.id)),!Se&&Ro.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),Ro.delete(H.id));let At=io(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",gt=Ku(H,Ki)+At,Ot=Ee||_e||Se?null:Ju(Lo,H.id,gt);if(Ot){x.appendChild(Ot.cloneNode(!0)),io(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(ie.add(H.toolCall.id),ms(H,o,Re.composerOverlay));return}let mt=null,Yt=s.find($e=>!!(H.variant==="reasoning"&&$e.renderReasoning||H.variant==="tool"&&$e.renderToolCall||!H.variant&&$e.renderMessage)),It=o.layout?.messages;if(io(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){ar.delete(H.id),l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(Wa(H)&&o.features?.suggestReplies?.enabled!==!1)return;if(io(H)&&o.features?.askUserQuestion?.enabled!==!1){let $e=s.find($t=>typeof $t.renderAskUserQuestion=="function");if($e&&ct.current){let $t=ar.get(H.id),jt=$t!==gt,wt=null;if(jt){let{payload:Qe,complete:We}=lo(H),bt=H.id,Ut=()=>ct.current?.getMessages().find(fn=>fn.id===bt);wt=$e.renderAskUserQuestion({message:H,payload:Qe,complete:We,resolve:fn=>{let ss=Ut();ss&&ct.current?.resolveAskUserQuestion(ss,fn)},dismiss:()=>{let fn=Ut();fn?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(fn),ct.current?.resolveAskUserQuestion(fn,"(dismissed)"))},config:o})}let dt=$t!=null;if(jt&&wt===null&&!dt){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(ie.add(H.toolCall.id),ms(H,o,Re.composerOverlay));return}let ht=Ho(H.id,H.role);ht.setAttribute("data-ask-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),se.push({messageId:H.id,fingerprint:gt,bubble:wt});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(ie.add(H.toolCall.id),ms(H,o,Re.composerOverlay));return}}else if(_e){let $e=s.find(dt=>typeof dt.renderApproval=="function")??a,jt=Qn.get(H.id)!==gt,wt=null;if(jt&&$e?.renderApproval){let dt=H.id,ht=(Qe,We)=>{let bt=ct.current?.getMessages().find(Ut=>Ut.id===dt);bt?.approval&&(bt.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(bt.id,Qe):ct.current?.resolveApproval(bt.approval,Qe,We))};wt=$e.renderApproval({message:H,defaultRenderer:()=>vi(H,o),config:o,approve:Qe=>ht("approved",Qe),deny:Qe=>ht("denied",Qe)})}if(jt&&wt===null)l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),Qn.delete(H.id),mt=vi(H,o);else{let dt=Ho(H.id,H.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),x.appendChild(dt),tt.push({messageId:H.id,fingerprint:gt,bubble:wt});return}}else if(Yt)if(H.variant==="reasoning"&&H.reasoning&&Yt.renderReasoning){if(!me)return;mt=Yt.renderReasoning({message:H,defaultRenderer:()=>pc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&Yt.renderToolCall){if(!Z)return;mt=Yt.renderToolCall({message:H,defaultRenderer:()=>fc(H,o),config:o})}else Yt.renderMessage&&(mt=Yt.renderMessage({message:H,defaultRenderer:()=>{let $e=$s(H,h,It,o.messageActions,Pe,{loadingIndicatorRenderer:L,widgetConfig:o});return H.role!=="user"&&wc($e,H,o,_),$e},config:o}));if(!mt&&Se){let $e=kc(H);if($e){let $t=Ro.get(H.id),jt=$t!==gt,wt=o.wrapComponentDirectiveInBubble!==!1&&Ln.getOptions($e.component)?.bubbleChrome!==!1,dt=null;if(jt){let ht=Ec($e,{config:o,message:H,transform:h});if(ht&&$e.component==="PersonaArtifactInline"){let Qe=ht.hasAttribute("data-artifact-inline")?ht:ht.querySelector("[data-artifact-inline]"),We=Qe?.getAttribute("data-artifact-inline")??"",bt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,Ut=We?l.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${bt}"]`)??null:null;Qe&&Ut&&Ut!==Qe&&ju(Ut)&&(Qe===ht?ht=Ut:Qe.replaceWith(Ut))}if(ht)if(wt){let Qe=document.createElement("div");if(Qe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Qe.id=`bubble-${H.id}`,Qe.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Qe.appendChild(We)}Qe.appendChild(ht),dt=Qe}else{let Qe=document.createElement("div");if(Qe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Qe.id=`bubble-${H.id}`,Qe.setAttribute("data-message-id",H.id),Qe.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Qe.appendChild(We)}Qe.appendChild(ht),dt=Qe}}if(dt||$t!=null){let ht=Ho(H.id,H.role);ht.setAttribute("data-component-directive-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Ce.push({messageId:H.id,fingerprint:gt,bubble:dt});return}}}if(!mt)if(H.variant==="reasoning"&&H.reasoning){if(!me)return;mt=pc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!Z)return;mt=fc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;mt=vi(H,o)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&H.role==="user"?mt=$e.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):$e?.renderAssistantMessage&&H.role==="assistant"?mt=$e.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):mt=$s(H,h,$e,o.messageActions,Pe,{loadingIndicatorRenderer:L,widgetConfig:o}),H.role!=="user"&&mt&&wc(mt,H,o,_)}let ke=Ho(H.id,H.role);ke.appendChild(mt),Xu(Lo,H.id,gt,ke),x.appendChild(ke)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let _e=Ee.getAttribute("data-persona-ask-sheet-for");_e&&!ie.has(_e)&&jo(Re.composerOverlay,_e)}),o.features?.toolCallDisplay?.grouped){let H=[],Ee=[],_e=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&Z){Ee.push(Se);return}Se.variant==="reasoning"&&!me||((Ee.length>1||_e&&Ee.length>0)&&H.push(Ee),Ee=[])}),(Ee.length>1||_e&&Ee.length>0)&&H.push(Ee),H.forEach(Se=>{let At=Se.map($e=>Array.from(x.children).find($t=>$t instanceof HTMLElement&&$t.getAttribute("data-wrapper-id")===$e.id)).filter($e=>!!$e);if(At.length<(_e?1:2))return;let gt=Ho(`tool-group-${Se[0].id}`,"assistant");gt.setAttribute("data-persona-tool-group-row","true");let Ot=document.createElement("div");Ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ot.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mt.id=`tool-group-summary-${Se[0].id}`;let Yt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,It=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map($e=>$e.toolCall).filter($e=>!!$e),defaultSummary:Yt,config:o});J(mt,It)||(mt.textContent=Yt);let ke=document.createElement("div");ke.className="persona-tool-group-stack persona-flex persona-flex-col",ke.id=`tool-group-stack-${Se[0].id}`,ke.setAttribute("data-persona-tool-group-stack","true"),Ot.appendChild(mt),_e||Ot.appendChild(ke),gt.appendChild(Ot),At[0].before(gt),At.forEach(($e,$t)=>{if(_e){$e.remove();return}$e.style.setProperty("--persona-message-row-max-width","100%");let jt=document.createElement("div");jt.className="persona-tool-group-item persona-relative",jt.setAttribute("data-persona-tool-group-item","true"),$t<At.length-1&&jt.setAttribute("data-persona-tool-group-connector","true"),jt.appendChild($e),ke.appendChild(jt)})})}Yu(Lo,N);let nn=g.some(H=>H.role==="assistant"&&H.streaming),Mt=g[g.length-1],Rt=Mt?.role==="assistant"&&!Mt.streaming&&Mt.variant!=="approval";if(bn&&g.some(H=>H.role==="user")&&!nn&&!Rt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Pr},Ee=s.find(Se=>Se.renderLoadingIndicator),_e=null;if(Ee?.renderLoadingIndicator&&(_e=Ee.renderLoadingIndicator(H)),_e===null&&o.loadingIndicator?.render&&(_e=o.loadingIndicator.render(H)),_e===null&&(_e=Pr()),_e){let Se=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1,gt=o.layout?.messages?.layout??"bubble";Se.className=At?dc("assistant",gt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Se.setAttribute("data-typing-indicator","true"),At&&(Se.style.color="var(--persona-message-assistant-text, var(--persona-text))",gt!=="flat"&&(Se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Se.appendChild(_e);let Ot=Ho("typing-indicator","assistant");Ot.appendChild(Se),x.appendChild(Ot)}}if(!bn&&g.length>0){let H=g[g.length-1],Ee={config:o,lastMessage:H,messageCount:g.length},_e=s.find(At=>At.renderIdleIndicator),Se=null;if(_e?.renderIdleIndicator&&(Se=_e.renderIdleIndicator(Ee)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Ee)),Se){let At=document.createElement("div"),gt=o.loadingIndicator?.showBubble!==!1;At.className=gt?["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(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Se);let Ot=Ho("idle-indicator","assistant");Ot.appendChild(At),x.appendChild(Ot)}}if(yp(x),ni(l,x),hl(l),se.length>0)for(let{messageId:H,fingerprint:Ee,bubble:_e}of se){let Se=l.querySelector(`#wrapper-${H}`);Se&&(ma(Se,G.get(H)??"assistant"),_e!==null&&(Se.replaceChildren(_e),Se.setAttribute("data-bubble-fp",Ee),ar.set(H,Ee)))}if(ar.size>0)for(let H of ar.keys())N.has(H)||ar.delete(H);if(Ce.length>0)for(let{messageId:H,fingerprint:Ee,bubble:_e}of Ce){let Se=l.querySelector(`#wrapper-${H}`);Se&&(ma(Se,G.get(H)??"assistant"),_e!==null&&(Se.replaceChildren(_e),Se.setAttribute("data-bubble-fp",Ee),Ro.set(H,Ee)))}if(Ro.size>0)for(let H of Ro.keys())N.has(H)||Ro.delete(H);if(tt.length>0)for(let{messageId:H,fingerprint:Ee,bubble:_e}of tt){let Se=l.querySelector(`#wrapper-${H}`);Se&&(ma(Se,G.get(H)??"assistant"),_e!==null&&(Se.replaceChildren(_e),Se.setAttribute("data-bubble-fp",Ee),Qn.set(H,Ee)))}if(Qn.size>0)for(let H of Qn.keys())N.has(H)||Qn.delete(H)},Xr=(l,g,h)=>{om(l,g,h),nd()},Yr=null,rm=()=>{if(Yr)return;let l=h=>{let x=h.composedPath();x.includes(De)||Ze&&x.includes(Ze)||ut(!1,"user")};Yr=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},xd=()=>{if(!Yr)return;(e.ownerDocument??document).removeEventListener("pointerdown",Yr,!0),Yr=null};qe.push(()=>xd());let Qr=null,sm=()=>{if(Qr)return;let l=h=>{h.key==="Escape"&&(h.isComposing||ut(!1,"user"))};Qr=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Cd=()=>{if(!Qr)return;(e.ownerDocument??document).removeEventListener("keydown",Qr,!0),Qr=null};qe.push(()=>Cd());let Zr=!1,wd=new Set,am=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},lr=()=>{if(!D())return;let l=Re.peekBanner,g=Re.peekTextNode;if(!l||!g)return;if(X){l.classList.remove("persona-pill-peek--visible");return}let h=_?.getMessages()??[],x;for(let Mt=h.length-1;Mt>=0;Mt--){let Rt=h[Mt];if(Rt.role==="assistant"&&Rt.content){x=Rt;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,L=!!x.streaming,J=am(),N=ai(J),G=N.type!=="none"?Er(N.type,J?.plugins):null,ie=G?.isAnimating?.(x)===!0,ge=G!==null&&(L||ie);ge&&G&&!wd.has(G.name)&&(ci(G,e),wd.add(G.name));let se=ge&&G?.containerClass?G.containerClass:null,Ce=g.dataset.personaPeekStreamClass??null;Ce&&Ce!==se&&(g.classList.remove(Ce),delete g.dataset.personaPeekStreamClass),se&&Ce!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),ge?(g.style.setProperty("--persona-stream-step",`${N.speed}ms`),g.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ve=ge?ii(A,N.buffer,G,x,L):A;if(ge&&N.placeholder==="skeleton"&&L&&(!Ve||!Ve.trim())){let Mt=document.createElement("div"),Rt=Ds();Rt.classList.add("persona-pill-peek__skeleton"),Mt.appendChild(Rt),ni(g,Mt)}else{let Mt=Math.max(0,Ve.length-100),Rt=Ve.length>100?Ve.slice(-100):Ve,H=jn(Rt);if(!ge||!G){let Ee=Ve.length>100?`\u2026${Rt}`:Rt;g.textContent!==Ee&&(g.textContent=Ee)}else{let Ee=H;(G.wrap==="char"||G.wrap==="word")&&(Ee=Bs(H,G.wrap,`peek-${x.id}`,{skipTags:G.skipTags,startIndex:Mt}));let _e=document.createElement("div");if(_e.innerHTML=Ee,G.useCaret&&Rt.length>0){let Se=li(),At=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),gt=At[At.length-1];gt?.parentNode?gt.parentNode.insertBefore(Se,gt.nextSibling):_e.appendChild(Se)}ni(g,_e),G.onAfterRender?.({container:g,bubble:l,messageId:x.id,message:x,speed:N.speed,duration:N.duration})}}let nn=bn||Zr;l.classList.toggle("persona-pill-peek--visible",nn)};if(D()){let l=Re.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),ut(!0,"user")};l.addEventListener("pointerdown",x),qe.push(()=>{l.removeEventListener("pointerdown",x)})}let g=()=>{Zr||(Zr=!0,lr())},h=()=>{Zr&&(Zr=!1,lr())};de.addEventListener("pointerenter",g),de.addEventListener("pointerleave",h),qe.push(()=>{de.removeEventListener("pointerenter",g),de.removeEventListener("pointerleave",h)}),Ze&&(Ze.addEventListener("pointerenter",g),Ze.addEventListener("pointerleave",h),qe.push(()=>{Ze.removeEventListener("pointerenter",g),Ze.removeEventListener("pointerleave",h)}))}let im=l=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",x=g.bottomOffset??"16px",A=g.collapsedMaxWidth,L=g.expandedMaxWidth??"880px",J=g.expandedTopOffset??"5vh",N=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",ie="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",se=De.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Ze){let Ce=Ze.style;Ce.bottom=x,Ce.width=A??""}if(l&&h!=="fullscreen"){if(h==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=N,se.maxWidth=ie,se.maxHeight=G,se.height=G;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${x} + ${ge})`,se.top=J,se.width=L,se.maxWidth=ie}},es=()=>{if(!$())return;if(D()){let ie=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=X?"expanded":"collapsed";De.dataset.state=ge,De.dataset.expandedSize=ie,Ze&&(Ze.dataset.state=ge,Ze.dataset.expandedSize=ie),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),im(X),fe.style.display=X?"flex":"none",ra(),X?(rm(),sm()):(xd(),Cd()),lr();return}let l=Ht(o),g=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=h,L=x&&A&&k,J=sn(o).reveal;X?(De.style.removeProperty("display"),De.style.display=l?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Nt?Nt.element.style.display="none":Kt&&(Kt.style.display="none")):(l?l&&(J==="overlay"||J==="push")&&!L?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Nt?Nt.element.style.display=l?"none":"":Kt&&(Kt.style.display=l?"none":""))},ut=(l,g="user")=>{if(!$()||X===l)return;let h=X;X=l,es();let x=(()=>{let L=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,ie=J.innerWidth<=G,ge=Ht(o)&&N&&ie,se=D()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||N&&ie&&k||ge||se})();if(X&&x){if(!Sn){let L=e.getRootNode(),J=L instanceof ShadowRoot?L.host:e.closest(".persona-host");J&&(Sn=oc(J,o.launcher?.zIndex??Vt))}Tn||(Tn=rc(e.ownerDocument))}else X||(Sn?.(),Sn=null,Tn?.(),Tn=null);X&&(os(),yd()||(ln()==="follow"?no(!0):md()));let A={open:X,source:g,timestamp:Date.now()};X&&!h?d.emit("widget:opened",A):!X&&h&&d.emit("widget:closed",A),d.emit("widget:state",{open:X,launcherEnabled:k,voiceActive:Je.active,streaming:_.isStreaming()})},tl=l=>{ot(l?"stop":"send"),V&&(V.disabled=l),aa.buttons.forEach(g=>{g.disabled=l}),Y.dataset.personaComposerStreaming=l?"true":"false",Y.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},nl=()=>{Je.active||ue&&ue.focus()};d.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>nl(),200)});let Ad=()=>{v.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",R.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ue.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=ae.querySelector("[data-persona-intro-card]");if(l){let h=o.copy?.showWelcomeCard!==!1;l.style.display=h?"":"none",h?(ae.classList.remove("persona-gap-3"),ae.classList.add("persona-gap-6")):(ae.classList.remove("persona-gap-6"),ae.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(we.textContent=o.copy?.sendButtonLabel??"Send"),ue.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ue.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 Bo=null,lm=()=>{Bo==null&&(Bo=setInterval(()=>{let l=Le.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Bo),Bo=null;return}let g=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Ba(g-x))})},100))},ol=(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((J,N)=>ol(J,g[N]));let h=l,x=g,A=Object.keys(h),L=Object.keys(x);return A.length===L.length&&A.every(J=>Object.prototype.hasOwnProperty.call(x,J)&&ol(h[J],x[J]))},Sd=l=>{let{content:g,rawContent:h,llmContent:x,...A}=l;return A},rl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!ki(l),cm=(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))&&rl(x)&&rl(A)&&ol(Sd(x),Sd(A))},Td=null,cr=null,Do=null,On=null,ha=l=>{Td=l;let g,h;cr=null;for(let A=l.length-1;A>=0;A-=1){let L=l[A];if(!g&&L.role==="user"&&(g=L),!h&&L.role==="assistant"&&(h=L),!cr&&rl(L)&&(cr={index:A,id:L.id}),g&&h&&cr)break}Xr(Le,l,re),Yl(Le,hn.artifacts,{suppressTransition:bn}),lm(),Vi(l),no(!bn),nm(l),l.length===0&&(Jr(),Vr=!0,ca=!1,da=null,pa=!1),!Gi||la?(Gi=!0,qr=g?.id??null,Ji=h?.id??null):g&&g.id!==qr?(qr=g.id,Zg(g.id)):h&&h.id!==Ji&&em(),h&&(Ji=h.id),tm(l);let x=Je.lastUserMessageId;g&&g.id!==x&&(Je.lastUserMessageId=g.id,d.emit("user:message",g)),Je.lastUserMessageWasVoice=!!g?.viaVoice,Qi(l),lr()},sl=()=>{On!==null&&(cancelAnimationFrame(On),On=null);let l=Do;Do=null,l&&ha(l)},Md=()=>{On!==null&&cancelAnimationFrame(On),On=null,Do=null},dm=l=>{let g=Do??Td;if(bn&&g&&cr&&cm(g,l,cr)){Do=l,On===null&&(On=requestAnimationFrame(()=>{On=null;let h=Do;Do=null,h&&ha(h)}));return}if(l.length===0){Md(),ha(l);return}sl(),ha(l)};_=new Ss(o,{onMessagesChanged(l){dm(l)},onStatusChanged(l){let g=o.statusIndicator??{};kt(O,(x=>x==="idle"?g.idleText??Wt.idle:x==="connecting"?g.connectingText??Wt.connecting:x==="connected"?g.connectedText??Wt.connected:x==="error"?g.errorText??Wt.error:x==="paused"?g.pausedText??Wt.paused:x==="resuming"?g.resumingText??Wt.resuming:Wt[x])(l),g,l)},onStreamingChanged(l){l||(_?.getMessages().length===0?Md():sl()),bn=l,tl(l),_&&Xr(Le,_.getMessages(),re),l||no(!0),tn(),Gc(l?"Responding\u2026":"Response complete."),lr()},onVoiceStatusChanged(l){if(d.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Nn(),pr();break;case"processing":Nn(),Cm();break;case"speaking":Nn(),wm();break;default:l==="idle"&&_.isBargeInActive()?(Nn(),pr(),V?.setAttribute("aria-label","End voice session")):(Je.active=!1,Nn(),Dn("system"),xn());break}},onArtifactsState(l){hn=l,l.artifacts.length===0&&(or=!1),Yl(Le,l.artifacts,{suppressTransition:bn}),Bn(),Qi()},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})}}),ct.current=_,qe.push(()=>_.cancel());let al=null;if(_.onReadAloudChange((l,g)=>{ed=l,td=g,nd();let h=l??al;l&&(al=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"&&(al=null)}),Gi=!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)}),(Me||o.onSSEEvent)&&_.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),Be?.processEvent(l,g),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let Ed=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};b?b.then(l=>{if(l){if(l.metadata&&(u=Rc(l.metadata),M.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(()=>Ed()):Ed();let kd=()=>{!D()||X||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},pm=(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),aw(A)}}:l:g,um=()=>{let g=ue.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},ts=!1,fm=async l=>{let g=ue.value.trim(),h=Tt?.hasAttachments()??!1,x=g?await(Zt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){ue.value="",ue.style.height="auto",ns(),Zt?.clear();return}let A=Zt?.collectForSubmit()??null,L=x?.kind==="server"?x.mentions:null,J=pm(A,L),N=x?.kind==="prompt"?x.sendText:g,G=!!A&&A.refs.length>0;if(!N&&!h&&!G&&!L)return;kd();let ie;h&&(ie=[],ie.push(...Tt.getContentParts()),N&&ie.push(zo(N)));let ge=x?.kind==="prompt"?void 0:um();ue.value="",ue.style.height="auto",ns(),_.sendMessage(N,{contentParts:ie,mentions:J??void 0,contentSegments:ge,viaVoice:l?.viaVoice}),h&&Tt.clearAttachments(),A&&Zt?.clear()},il=async l=>{if(!ts){ts=!0;try{await fm(l)}finally{ts=!1}}},Pd=l=>{if(l.preventDefault(),_.isStreaming()){_.cancel(),Be?.reset(),Oe?.update();return}ts||il()},gm=()=>o.features?.composerHistory!==!1,ll={...ec},cl=!1,ns=()=>{ll={...ec}},mm=()=>_.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),hm=l=>{if(!ue)return;cl=!0,ue.value=l,ue.dispatchEvent(new Event("input",{bubbles:!0})),cl=!1;let g=ue.value.length;ue.setSelectionRange(g,g)},ym=l=>{cl||(l.isComposing||Zt?.handleInput(l.inputType??void 0),ns())},bm=l=>{if(ue&&!(!l.isComposing&&Zt?.handleKeydown(l))){if(gm()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=ue.selectionStart===0&&ue.selectionEnd===0,h=Vu({direction:l.key==="ArrowUp"?"up":"down",history:mm(),currentValue:ue.value,atStart:g,state:ll});if(ll=h.state,h.handled){l.preventDefault(),h.value!==void 0&&hm(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}if(ts){l.preventDefault();return}ns(),l.preventDefault(),we.click()}}},Ld=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(fe)&&(_.cancel(),Be?.reset(),Oe?.update(),ns(),l.preventDefault(),l.stopImmediatePropagation())},vm=async l=>{if(o.attachments?.enabled!==!0||!Tt)return;let g=nw(l.clipboardData);g.length!==0&&(l.preventDefault(),await Tt.handleFiles(g))},pn=null,Mn=!1,dr=null,Ct=null,Rd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ya=(l="user")=>{if(Mn||_.isStreaming())return;let g=Rd();if(!g)return;pn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let A=ue.value;pn.onresult=L=>{let J="",N="";for(let ie=0;ie<L.results.length;ie++){let ge=L.results[ie],se=ge[0].transcript;ge.isFinal?J+=se+" ":N=se}let G=A+J+N;ue.value=G,dr&&clearTimeout(dr),(J||N)&&(dr=window.setTimeout(()=>{ue.value.trim()&&pn&&Mn&&(oo(),il({viaVoice:!0}))},x))},pn.onerror=L=>{L.error!=="no-speech"&&oo()},pn.onend=()=>{if(Mn){let L=ue.value.trim();L&&L!==A.trim()&&il({viaVoice:!0}),oo()}};try{if(pn.start(),Mn=!0,Je.active=!0,l!=="system"&&(Je.manuallyDeactivated=!1),Dn(l),xn(),V){let L=o.voiceRecognition??{};Ct={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let J=L.recordingBackgroundColor,N=L.recordingIconColor,G=L.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let ie=V.querySelector("svg");ie&&ie.setAttribute("stroke",N)}G&&(V.style.borderColor=G),V.setAttribute("aria-label","Stop voice recognition")}}catch{oo("system")}},oo=(l="user")=>{if(Mn){if(Mn=!1,dr&&(clearTimeout(dr),dr=null),pn){try{pn.stop()}catch{}pn=null}if(Je.active=!1,Dn(l),xn(),V){if(V.classList.remove("persona-voice-recording"),Ct){V.style.backgroundColor=Ct.backgroundColor,V.style.color=Ct.color,V.style.borderColor=Ct.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}V.setAttribute("aria-label","Start voice recognition")}}},xm=(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 J=m("div","persona-send-button-wrapper"),N=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let G=l?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",G);let ie=l?.iconName??"mic",ge=g?.size??"40px",se=l?.iconSize??ge,Ce=parseFloat(se)||24,Ve=l?.backgroundColor??g?.backgroundColor,ft=l?.iconColor??g?.textColor;N.style.width=se,N.style.height=se,N.style.minWidth=se,N.style.minHeight=se,N.style.fontSize="18px",N.style.lineHeight="1",ft?N.style.color=ft:N.style.color="var(--persona-text, #111827)";let nn=oe(ie,Ce,ft||"currentColor",1.5);nn?N.appendChild(nn):N.textContent="\u{1F3A4}",Ve?N.style.backgroundColor=Ve:N.style.backgroundColor="",l?.borderWidth&&(N.style.borderWidth=l.borderWidth,N.style.borderStyle="solid"),l?.borderColor&&(N.style.borderColor=l.borderColor),l?.paddingX&&(N.style.paddingLeft=l.paddingX,N.style.paddingRight=l.paddingX),l?.paddingY&&(N.style.paddingTop=l.paddingY,N.style.paddingBottom=l.paddingY),J.appendChild(N);let Mt=l?.showTooltip??!1;return _t({anchor:N,trigger:J,text:()=>N.getAttribute("aria-label")??G,enabled:Mt}),{micButton:N,micButtonWrapper:J}},dl=()=>{if(!V||Ct)return;let l=o.voiceRecognition??{};Ct={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},pl=(l,g)=>{if(!V)return;let h=V.querySelector("svg");h&&h.remove();let x=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=oe(l,x,g,1.5);A&&V.appendChild(A)},ba=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},pr=()=>{if(!V)return;dl();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(ba(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=V.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(V.style.borderColor=x),V.setAttribute("aria-label","Stop voice recognition")},Cm=()=>{if(!V)return;dl();let l=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),h=l.processingIconName??"loader",x=l.processingIconColor??Ct?.color??"",A=l.processingBackgroundColor??Ct?.backgroundColor??"",L=l.processingBorderColor??Ct?.borderColor??"";ba(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=L;let J=x||"currentColor";V.style.color=J,pl(h,J),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},wm=()=>{if(!V)return;dl();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??Ct?.color??"":Ct?.color??""),L=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),J=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":Ct?.borderColor??"");ba(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=L,V.style.borderColor=J;let N=A||"currentColor";V.style.color=N,pl(x,N);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",G),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},Nn=()=>{V&&(ba(),Ct&&(V.style.backgroundColor=Ct.backgroundColor??"",V.style.color=Ct.color??"",V.style.borderColor=Ct.borderColor??"",pl(Ct.iconName,Ct.color||"currentColor"),Ct=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},va=()=>{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(()=>{Je.active=!1,Je.manuallyDeactivated=!0,xn(),Dn("user"),Nn()});return}_.toggleVoice().then(()=>{Je.active=_.isVoiceActive(),Je.manuallyDeactivated=!_.isVoiceActive(),xn(),Dn("user"),_.isVoiceActive()?pr():Nn()});return}if(Mn){let l=ue.value.trim();Je.manuallyDeactivated=!0,xn(),oo("user"),l&&(ue.value="",ue.style.height="auto",_.sendMessage(l))}else Je.manuallyDeactivated=!1,xn(),ya("user")};Xc=va,V&&(V.addEventListener("click",va),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Nn()):oo("system"),V&&V.removeEventListener("click",va)}));let Am=d.on("assistant:complete",()=>{cd&&(Je.active||Je.manuallyDeactivated||cd==="assistant"&&!Je.lastUserMessageWasVoice||setTimeout(()=>{!Je.active&&!Je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Je.active=_.isVoiceActive(),Dn("auto"),_.isVoiceActive()&&pr()}):ya("auto"))},600))});qe.push(Am);let Sm=d.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});qe.push(Sm);let Id=()=>{ut(!X,"user")},Nt=null,Kt=null;if(k&&!D()){let{instance:l,element:g}=ic({config:o,plugins:s,onToggle:Id});Nt=l,l||(Kt=g)}Nt?e.appendChild(Nt.element):Kt&&e.appendChild(Kt),es(),Vi(),Ad(),tl(_.isStreaming()),yd()||(ln()==="follow"?no(!0):md()),Kg(),z&&(!k||D()?setTimeout(()=>nl(),0):X&&setTimeout(()=>nl(),200));let os=()=>{if(D()){nr(),es();return}let l=Ht(o),g=o.launcher?.sidebarMode??!1,h=l||g||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640,J=x.innerWidth<=L,N=A&&J&&k;try{if(N){$r(),jr=oa();return}let G=!1;ee&&(ee=!1,$r(),G=!0);let ie=oa();if(!G&&ie!==jr&&($r(),G=!0),jr=ie,G&&zi(),!k&&!l){de.style.height="",de.style.width="";return}if(!g&&!l){let se=o?.launcher?.width??o?.launcherWidth??mn;de.style.width=se,de.style.maxWidth=se}if(na(),!h){let ge=x.innerHeight,se=64,Ce=o.launcher?.heightOffset??0,Ve=Math.max(200,ge-se),ft=Math.min(640,Ve),tt=Math.max(200,ft-Ce);de.style.height=`${tt}px`}}finally{if(nr(),es(),X&&k){let ie=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,se=o.launcher?.mobileFullscreen??!0,Ce=Ht(o)&&se&&ie,Ve=ge||se&&ie&&k||Ce;if(Ve&&!Tn){let ft=e.getRootNode(),tt=ft instanceof ShadowRoot?ft.host:e.closest(".persona-host");tt&&!Sn&&(Sn=oc(tt,o.launcher?.zIndex??Vt)),Tn=rc(e.ownerDocument)}else Ve||(Sn?.(),Sn=null,Tn?.(),Tn=null)}}};os();let Wd=e.ownerDocument.defaultView??window;if(Wd.addEventListener("resize",os),qe.push(()=>Wd.removeEventListener("resize",os)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{nr()});l.observe(Y),qe.push(()=>l.disconnect())}cn=ae.scrollTop;let Hd=Rn(ae),Bd=()=>{let l=ae.scrollTop,g=Rn(ae),h=g<Hd;if(Hd=g,!Gn()){cn=l,tn();return}let{action:x,nextLastScrollTop:A}=ri({following:en.isFollowing(),currentScrollTop:l,lastScrollTop:cn,nearBottom:vo(ae,ua),userScrollThreshold:qg,isAutoScrolling:dn||ia||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=A,x==="resume"){ga()||to();return}x==="pause"&&Gr()};if(ae.addEventListener("scroll",Bd,{passive:!0}),qe.push(()=>ae.removeEventListener("scroll",Bd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Qg(),hl(Le)});l.observe(Le),l.observe(ae),qe.push(()=>l.disconnect())}let Dd=()=>{Gn()&&en.isFollowing()&&ga()&&Gr()},Od=ae.ownerDocument;Od.addEventListener("selectionchange",Dd),qe.push(()=>{Od.removeEventListener("selectionchange",Dd)});let Tm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Nd=l=>{Tm.has(l.key)&&(Wo(),qc()&&Gn()&&en.isFollowing()&&Gr())},Fd=l=>{l.target?.closest("a, button, [tabindex], input, textarea, select")&&(Wo(),qc()&&Gn()&&en.isFollowing()&&Gr())};ae.addEventListener("keydown",Nd),ae.addEventListener("focusin",Fd),qe.push(()=>{ae.removeEventListener("keydown",Nd),ae.removeEventListener("focusin",Fd)});let _d=l=>{if(l.deltaY!==0&&Wo(),!Gn())return;let g=si({following:en.isFollowing(),deltaY:l.deltaY,nearBottom:vo(ae,ua),resumeWhenNearBottom:!0});g==="pause"?Gr():g==="resume"&&!ga()&&to()};ae.addEventListener("wheel",_d,{passive:!0}),ae.addEventListener("touchmove",Wo,{passive:!0}),ae.addEventListener("pointerdown",Wo,{passive:!0}),qe.push(()=>{ae.removeEventListener("touchmove",Wo),ae.removeEventListener("pointerdown",Wo)}),qe.push(()=>ae.removeEventListener("wheel",_d)),Pt.addEventListener("click",()=>{Jr(),ae.scrollTop=ae.scrollHeight,cn=ae.scrollTop,to(),no(!0),tn()}),qe.push(()=>Pt.remove()),qe.push(()=>{ud(),Jr()});let $d=()=>{T&&(Po&&(T.removeEventListener("click",Po),Po=null),$()?(T.style.display="",Po=()=>{ut(!1,"user")},T.addEventListener("click",Po)):T.style.display="none")};$d(),(()=>{let{clearChatButton:l}=Re;l&&l.addEventListener("click",()=>{_.clearMessages(),Lo.clear(),to(),jo(Re.composerOverlay);try{localStorage.removeItem(Dr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Dr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Dr)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&&Yi(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},M.syncFromMetadata(),Me?.clear(),Be?.reset(),Oe?.update()})})(),S&&S.addEventListener("submit",Pd);let jd=[["keydown",bm],["input",ym],["paste",vm],["focus",_g]],Ud=l=>{if(l)for(let[g,h]of jd)l.addEventListener(g,h)},zd=l=>{if(l)for(let[g,h]of jd)l.removeEventListener(g,h)};Ud(ue),Zt?.onComposerSwap((l,g)=>{zd(g),ue=l,Ud(l)});let qd=e.ownerDocument??document;qd.addEventListener("keydown",Ld,!0);let Vd="persona-attachment-drop-active",rs=0,ul=()=>{rs=0,fe.classList.remove(Vd)},ur=()=>o.attachments?.enabled===!0&&Tt!==null,Kd=l=>{!Pi(l.dataTransfer)||!ur()||(rs++,rs===1&&fe.classList.add(Vd))},Gd=l=>{!Pi(l.dataTransfer)||!ur()||(rs--,rs<=0&&ul())},Jd=l=>{!Pi(l.dataTransfer)||!ur()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Xd=l=>{if(!Pi(l.dataTransfer)||!ur())return;l.preventDefault(),l.stopPropagation(),ul();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&Tt.handleFiles(g)},ro=!0;fe.addEventListener("dragenter",Kd,ro),fe.addEventListener("dragleave",Gd,ro),e.addEventListener("dragover",Jd,ro),e.addEventListener("drop",Xd,ro);let xa=e.ownerDocument,Yd=l=>{ur()&&l.preventDefault()},Qd=l=>{ur()&&l.preventDefault()};xa.addEventListener("dragover",Yd),xa.addEventListener("drop",Qd),qe.push(()=>{S&&S.removeEventListener("submit",Pd),zd(ue),qd.removeEventListener("keydown",Ld,!0),Zt?.destroy()}),qe.push(()=>{fe.removeEventListener("dragenter",Kd,ro),fe.removeEventListener("dragleave",Gd,ro),e.removeEventListener("dragover",Jd,ro),e.removeEventListener("drop",Xd,ro),xa.removeEventListener("dragover",Yd),xa.removeEventListener("drop",Qd),ul()}),qe.push(()=>{_.cancel()}),Nt?qe.push(()=>{Nt?.destroy()}):Kt&&qe.push(()=>{Kt?.remove()});let Lt={update(l){let g=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,L=o.loadingIndicator,J=o.iterationDisplay,N=o.features?.showReasoning,G=o.features?.showToolCalls,ie=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type;o=Ti({...o,features:r},l),r=o.features,o=Ai(o),ra(),Ar(e,o),qs(e,o),Vs(e,o),Bn(),o.colorScheme!==A&&ld();let Ce=Si.getForInstance(o.plugins);s.length=0,s.push(...Ce),k=o.launcher?.enabled??!0,F=o.launcher?.autoExpand??!1,me=o.features?.showReasoning??!0,Z=o.features?.showToolCalls??!0,Q=o.features?.scrollToBottom??{};let Ve=ln();pe=o.features?.scrollBehavior??{},Ve!==ln()&&(Jr(),to()),Jc(),tn();let ft=ce;if(ce=o.features?.showEventStreamToggle??!1,ce&&!ft){if(Me||(Ae=new Us(he),Me=new js(at,Ae),Be=Be??new zs,Ae.open().then(()=>Me?.restore()).catch(()=>{}),_.setSSEEventCallback((ne,Ge)=>{o.onSSEEvent?.(ne,Ge),Be?.processEvent(ne,Ge),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!et&&j){let ne=o.features?.eventStream?.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne?.toggleButton?" "+ne.toggleButton:"");et=m("button",Ge),et.style.width="28px",et.style.height="28px",et.style.color=Jt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let yt=oe("activity","18px","currentColor",1.5);yt&&et.appendChild(yt);let nt=Re.clearChatButtonWrapper,st=Re.closeButtonWrapper,zt=nt||st;zt&&zt.parentNode===j?j.insertBefore(et,zt):j.appendChild(et),et.addEventListener("click",()=>{ze?Fr():_i()})}}else!ce&&ft&&(Fr(),et&&(et.remove(),et=null),Me?.clear(),Ae?.destroy(),Me=null,Ae=null,Be?.reset(),Be=null);if(o.launcher?.enabled===!1&&Nt&&(Nt.destroy(),Nt=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!Nt&&!Kt){let{instance:ne,element:Ge}=ic({config:o,plugins:s,onToggle:Id});Nt=ne,ne||(Kt=Ge),e.appendChild(Ge)}Nt&&Nt.update(o),K&&o.launcher?.title!==void 0&&(K.textContent=o.launcher.title),B&&o.launcher?.subtitle!==void 0&&(B.textContent=o.launcher.subtitle);let tt=o.layout?.header;if(tt?.layout!==q&&j){let ne=tt?Fs(o,tt,{showClose:$(),onClose:()=>ut(!1,"user")}):wo({config:o,showClose:$(),onClose:()=>ut(!1,"user")});St.replaceHeader(ne),j=St.header.element,I=St.header.iconHolder,K=St.header.headerTitle,B=St.header.headerSubtitle,T=St.header.closeButton,q=tt?.layout}else if(tt){if(I&&(I.style.display=tt.showIcon===!1?"none":""),K&&(K.style.display=tt.showTitle===!1?"none":""),B&&(B.style.display=tt.showSubtitle===!1?"none":""),T){let ne=$()&&tt.showCloseButton!==!1;T.style.display=ne?"":"none"}if(Re.clearChatButtonWrapper){let ne=tt.showClearChat;if(ne!==void 0){Re.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Ge}=Re;Ge&&!Ge.classList.contains("persona-absolute")&&(ne?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Mt=o.layout?.showHeader!==!1;j&&(j.style.display=Mt?"":"none");let Rt=o.layout?.showFooter!==!1;Y&&(Y.style.display=Rt?"":"none"),nr(),tn(),k!==U?k?ut(F,"auto"):(X=!0,es()):F!==w&&ut(F,"auto"),w=F,U=k,os(),$d();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(g),Se=JSON.stringify(o.messageActions)!==JSON.stringify(h),At=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),gt=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,Ot=o.iterationDisplay!==J,mt=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);(_e||Se||At||gt||Ot||mt)&&_&&(Ki++,Xr(Le,_.getMessages(),re));let It=o.features?.streamAnimation?.type;if(It!==se&&It&&It!=="none"){let ne=Er(It,o.features?.streamAnimation?.plugins);ne&&ci(ne,e)}let ke=o.launcher??{},$e=ke.headerIconHidden??!1,$t=o.layout?.header?.showIcon,jt=$e||$t===!1,wt=ke.headerIconName,dt=ke.headerIconSize??"48px";if(I){let ne=fe.querySelector(".persona-border-b-persona-divider"),Ge=ne?.querySelector(".persona-flex-col");if(jt)I.style.display="none",ne&&Ge&&!ne.contains(Ge)&&ne.insertBefore(Ge,ne.firstChild);else{if(I.style.display="",I.style.height=dt,I.style.width=dt,ne&&Ge&&(ne.contains(I)?I.nextSibling!==Ge&&(I.remove(),ne.insertBefore(I,Ge)):ne.insertBefore(I,Ge)),wt){let nt=parseFloat(dt)||24,st=oe(wt,nt*.6,"currentColor",1);st?I.replaceChildren(st):I.textContent=ke.agentIconText??"\u{1F4AC}"}else if(ke.iconUrl){let nt=I.querySelector("img");if(nt)nt.src=ke.iconUrl,nt.style.height=dt,nt.style.width=dt;else{let st=document.createElement("img");st.src=ke.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=dt,st.style.width=dt,I.replaceChildren(st)}}else{let nt=I.querySelector("svg"),st=I.querySelector("img");(nt||st)&&I.replaceChildren(),I.textContent=ke.agentIconText??"\u{1F4AC}"}let yt=I.querySelector("img");yt&&(yt.style.height=dt,yt.style.width=dt)}}let ht=o.layout?.header?.showTitle,Qe=o.layout?.header?.showSubtitle;if(K&&(K.style.display=ht===!1?"none":""),B&&(B.style.display=Qe===!1?"none":""),T){let ne=$()&&o.layout?.header?.showCloseButton!==!1;T.style.display=ne?"":"none";let Ge=ke.closeButtonSize??"32px",yt=ke.closeButtonPlacement??"inline";T.style.height=Ge,T.style.width=Ge;let{closeButtonWrapper:nt}=Re,st=yt==="top-right",zt=nt?.classList.contains("persona-absolute");if(nt&&st!==zt)if(nt.remove(),st)nt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(nt);else{let ao=ke.clearChat?.placement??"inline",is=ke.clearChat?.enabled??!0;nt.className=is&&ao==="inline"?"":"persona-ml-auto";let Zd=fe.querySelector(".persona-border-b-persona-divider");Zd&&Zd.appendChild(nt)}if(T.style.color=ke.closeButtonColor||Jt.actionIconColor,ke.closeButtonBackgroundColor?(T.style.backgroundColor=ke.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),ke.closeButtonBorderWidth||ke.closeButtonBorderColor){let ao=ke.closeButtonBorderWidth||"0px",is=ke.closeButtonBorderColor||"transparent";T.style.border=`${ao} solid ${is}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");ke.closeButtonBorderRadius?(T.style.borderRadius=ke.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),ke.closeButtonPaddingX?(T.style.paddingLeft=ke.closeButtonPaddingX,T.style.paddingRight=ke.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),ke.closeButtonPaddingY?(T.style.paddingTop=ke.closeButtonPaddingY,T.style.paddingBottom=ke.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let on=ke.closeButtonIconName??"x",Cn=ke.closeButtonIconText??"\xD7";T.innerHTML="";let Ft=oe(on,"28px","currentColor",1);Ft?(Ft.style.display="block",T.appendChild(Ft)):T.textContent=Cn;let qt=ke.closeButtonTooltipText??"Close chat",_n=ke.closeButtonShowTooltip??!0;T.setAttribute("aria-label",qt),nt&&_t({anchor:T,trigger:nt,text:()=>T?.getAttribute("aria-label")??qt,enabled:_n})}let{clearChatButton:We,clearChatButtonWrapper:bt}=Re;if(We){let ne=ke.clearChat??{},Ge=ne.enabled??!0,yt=o.layout?.header?.showClearChat,nt=yt!==void 0?yt:Ge,st=ne.placement??"inline";if(bt){bt.style.display=nt?"":"none";let{closeButtonWrapper:zt}=Re;!D()&&zt&&!zt.classList.contains("persona-absolute")&&(nt?zt.classList.remove("persona-ml-auto"):zt.classList.add("persona-ml-auto"));let on=st==="top-right",Cn=bt.classList.contains("persona-absolute");if(!D()&&on!==Cn&&nt){if(bt.remove(),on)bt.className="persona-absolute persona-top-4 persona-z-50",bt.style.right="48px",fe.style.position="relative",fe.appendChild(bt);else{bt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bt.style.right="";let qt=fe.querySelector(".persona-border-b-persona-divider"),_n=Re.closeButtonWrapper;qt&&_n&&_n.parentElement===qt?qt.insertBefore(bt,_n):qt&&qt.appendChild(bt)}let Ft=Re.closeButtonWrapper;Ft&&!Ft.classList.contains("persona-absolute")&&(on?Ft.classList.add("persona-ml-auto"):Ft.classList.remove("persona-ml-auto"))}}if(nt){if(!D()){let ao=ne.size??"32px";We.style.height=ao,We.style.width=ao}let zt=ne.iconName??"refresh-cw",on=ne.iconColor??"";We.style.color=on||Jt.actionIconColor,We.innerHTML="";let Cn=D()?"14px":"20px",Ft=oe(zt,Cn,"currentColor",1);if(Ft&&(Ft.style.display="block",We.appendChild(Ft)),ne.backgroundColor?(We.style.backgroundColor=ne.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let ao=ne.borderWidth||"0px",is=ne.borderColor||"transparent";We.style.border=`${ao} solid ${is}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");ne.borderRadius?(We.style.borderRadius=ne.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),ne.paddingX?(We.style.paddingLeft=ne.paddingX,We.style.paddingRight=ne.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),ne.paddingY?(We.style.paddingTop=ne.paddingY,We.style.paddingBottom=ne.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let qt=ne.tooltipText??"Clear chat",_n=ne.showTooltip??!0;We.setAttribute("aria-label",qt),bt&&_t({anchor:We,trigger:bt,text:()=>We?.getAttribute("aria-label")??qt,enabled:_n})}}let Ut=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Mi],fn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Br.message,Br.messageAndClick];M=Ei({parsers:Ut,handlers:fn,getSessionMetadata:C,updateSessionMetadata:E,emit:d.emit,documentRef:typeof document<"u"?document:null}),re=eg(o,M,He),_.updateConfig(o),Xr(Le,_.getMessages(),re),Vi(),Ad(),tl(_.isStreaming());let ss=o.voiceRecognition?.enabled===!0,Ca=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Et=o.voiceRecognition?.provider?.type==="runtype";if(ss&&(Ca||Et))if(!V||!je){let ne=xm(o.voiceRecognition,o.sendButton);ne&&(V=ne.micButton,je=ne.micButtonWrapper,Ie.insertBefore(je,te),V.addEventListener("click",va),V.disabled=_.isStreaming())}else{let ne=o.voiceRecognition??{},Ge=o.sendButton??{},yt=ne.iconName??"mic",nt=Ge.size??"40px",st=ne.iconSize??nt,zt=parseFloat(st)||24;V.style.width=st,V.style.height=st,V.style.minWidth=st,V.style.minHeight=st;let on=ne.iconColor??Ge.textColor;V.innerHTML="";let Cn=oe(yt,zt,on||"currentColor",1.5);Cn?V.appendChild(Cn):V.textContent="\u{1F3A4}";let Ft=ne.backgroundColor??Ge.backgroundColor;Ft?V.style.backgroundColor=Ft:V.style.backgroundColor="",on?V.style.color=on:V.style.color="var(--persona-text, #111827)",ne.borderWidth?(V.style.borderWidth=ne.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ne.borderColor?V.style.borderColor=ne.borderColor:V.style.borderColor="",ne.paddingX?(V.style.paddingLeft=ne.paddingX,V.style.paddingRight=ne.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ne.paddingY?(V.style.paddingTop=ne.paddingY,V.style.paddingBottom=ne.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let qt=ne.tooltipText??"Start voice recognition",_n=ne.showTooltip??!1;V.setAttribute("aria-label",qt),je&&_t({anchor:V,trigger:je,text:()=>V?.getAttribute("aria-label")??qt,enabled:_n}),je.style.display="",V.disabled=_.isStreaming()}else V&&je&&(je.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Mn&&oo());if(o.attachments?.enabled===!0){if(!Ue||!xe){let ne=o.attachments??{},yt=(o.sendButton??{}).size??"40px";Bt||(Bt=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Bt.style.display="none",S.insertBefore(Bt,ue)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(ne.allowedTypes??qn).join(","),Fe.multiple=(ne.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),S.insertBefore(Fe,ue)),Ue=m("div","persona-send-button-wrapper"),xe=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),xe.type="button",xe.setAttribute("aria-label",ne.buttonTooltipText??"Attach file");let nt=ne.buttonIconName??"paperclip",st=yt,zt=parseFloat(st)||40,on=Math.round(zt*.6);xe.style.width=st,xe.style.height=st,xe.style.minWidth=st,xe.style.minHeight=st,xe.style.fontSize="18px",xe.style.lineHeight="1";let Cn=oe(nt,on,"currentColor",1.5);Cn?xe.appendChild(Cn):xe.textContent="\u{1F4CE}",xe.addEventListener("click",qt=>{qt.preventDefault(),Fe?.click()}),Ue.appendChild(xe);let Ft=ne.buttonTooltipText??"Attach file";_t({anchor:xe,trigger:Ue,text:()=>xe?.getAttribute("aria-label")??Ft}),Xe?Xe.append(Ue):S.appendChild(Ue),!Tt&&Fe&&Bt&&(Tt=wr.fromConfig(ne),Tt.setPreviewsContainer(Bt),Fe.addEventListener("change",async()=>{Tt&&Fe?.files&&(await Tt.handleFileSelect(Fe.files),Fe.value="")}))}else{Ue.style.display="";let ne=o.attachments??{};Fe&&(Fe.accept=(ne.allowedTypes??qn).join(","),Fe.multiple=(ne.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(tg(o.attachments?.dropOverlay)),xe){let ne=o.attachments??{},Ge=ne.buttonTooltipText??"Attach file";xe.setAttribute("aria-label",Ge),xe.textContent="";let yt=parseFloat(o.sendButton?.size??"40px")||40,nt=oe(ne.buttonIconName??"paperclip",Math.round(yt*.6),"currentColor",1.5);nt?xe.appendChild(nt):xe.textContent="\u{1F4CE}",Ue&&_t({anchor:xe,trigger:Ue,text:()=>xe?.getAttribute("aria-label")??Ge})}}else Ue&&(Ue.style.display="none"),Tt&&Tt.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},as=Dt.useIcon??!1,Aa=Dt.iconText??"\u2191",fr=Dt.iconName,Sa=Dt.tooltipText??"Send message",fl=Dt.showTooltip??!1,Oo=Dt.size??"40px",Fn=Dt.backgroundColor,No=Dt.textColor;if(as){if(we.style.width=Oo,we.style.height=Oo,we.style.minWidth=Oo,we.style.minHeight=Oo,we.style.fontSize="18px",we.style.lineHeight="1",No?we.style.color=No:we.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(we.innerHTML="",fr){let ne=parseFloat(Oo)||24,Ge=No?.trim()||"currentColor",yt=oe(fr,ne,Ge,2);yt?we.appendChild(yt):we.textContent=Aa}else we.textContent=Aa;we.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn?(we.style.backgroundColor=Fn,we.classList.remove("persona-bg-persona-primary")):(we.style.backgroundColor="",we.classList.add("persona-bg-persona-primary"))}else we.textContent=o.copy?.sendButtonLabel??"Send",we.style.width="",we.style.height="",we.style.minWidth="",we.style.minHeight="",we.style.fontSize="",we.style.lineHeight="",we.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",Fn?(we.style.backgroundColor=Fn,we.classList.remove("persona-bg-persona-accent")):we.classList.add("persona-bg-persona-accent"),No?we.style.color=No:we.classList.add("persona-text-white");Dt.borderWidth?(we.style.borderWidth=Dt.borderWidth,we.style.borderStyle="solid"):(we.style.borderWidth="",we.style.borderStyle=""),Dt.borderColor?we.style.borderColor=Dt.borderColor:we.style.borderColor="",Dt.paddingX?(we.style.paddingLeft=Dt.paddingX,we.style.paddingRight=Dt.paddingX):(we.style.paddingLeft="",we.style.paddingRight=""),Dt.paddingY?(we.style.paddingTop=Dt.paddingY,we.style.paddingBottom=Dt.paddingY):(we.style.paddingTop="",we.style.paddingBottom=""),_.isStreaming()||we.setAttribute("aria-label",Sa),te&&_t({anchor:we,trigger:te,text:()=>we.getAttribute("aria-label")??Sa,enabled:fl});let Ta=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Ta?(Le.style.maxWidth=Ta,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",S&&(S.style.maxWidth=Ta,S.style.marginLeft="auto",S.style.marginRight="auto"),it&&(it.style.maxWidth=Ta,it.style.marginLeft="auto",it.style.marginRight="auto")):(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",S&&(S.style.maxWidth="",S.style.marginLeft="",S.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let so=o.statusIndicator??{},Mm=so.visible??!0;if(O.style.display=Mm?"":"none",_){let ne=_.getStatus();kt(O,(yt=>yt==="idle"?so.idleText??Wt.idle:yt==="connecting"?so.connectingText??Wt.connecting:yt==="connected"?so.connectedText??Wt.connected:yt==="error"?so.errorText??Wt.error:Wt[yt])(ne),so,ne)}O.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Em=so.align==="left"?"persona-text-left":so.align==="center"?"persona-text-center":"persona-text-right";O.classList.add(Em)},open(){$()&&ut(!0,"api")},close(){$()&&ut(!1,"api")},toggle(){$()&&ut(!X,"api")},reconnect(){_.reconnectNow()},clearChat(){Hn=!1,_.clearMessages(),Lo.clear(),to();try{localStorage.removeItem(Dr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Dr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Dr)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&&Yi(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},M.syncFromMetadata(),Me?.clear(),Be?.reset(),Oe?.update()},setMessage(l){return!ue||_.isStreaming()?!1:(!X&&$()&&ut(!0,"system"),ue.value=l,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let g=l?.trim()||ue.value.trim();return g?(!X&&$()&&ut(!0,"system"),ue.value="",ue.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!X&&$()&&ut(!0,"system"),Je.manuallyDeactivated=!1,xn(),_.toggleVoice().then(()=>{Je.active=_.isVoiceActive(),Dn("user"),_.isVoiceActive()&&pr()})),!0):Mn?!0:Rd()?(!X&&$()&&ut(!0,"system"),Je.manuallyDeactivated=!1,xn(),ya("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,xn(),Dn("user"),Nn()}),!0):!1:Mn?(Je.manuallyDeactivated=!0,xn(),oo("user"),!0):!1},injectMessage(l){return!X&&$()&&ut(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!X&&$()&&ut(!0,"system");let g=_.injectAssistantMessage(l);return ye&&(ye=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(l){return!X&&$()&&ut(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!X&&$()&&ut(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!X&&$()&&ut(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!X&&$()&&ut(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!X&&$()&&ut(!0,"system"),_.injectTestEvent(l)},async connectStream(l,g){return _.connectStream(l,g)},__pushEventStreamEvent(l){Me&&(Be?.processEvent(l.type,l.payload),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ce||!Me||_i()},hideEventStream(){ze&&Fr()},isEventStreamVisible(){return ze},showArtifacts(){Xt(o)&&(Hn=!1,or=!0,Bn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Hn=!0,Bn())},upsertArtifact(l){return Xt(o)?(Un(o.features?.artifacts,{artifactType:l.artifactType,...l.artifactType==="markdown"&&l.file?{file:l.file}:{},...l.presentation?{presentation:l.presentation}:{}})==="panel"&&(Hn=!1,or=!0),_.upsertArtifact(l)):null},selectArtifact(l){Xt(o)&&_.selectArtifact(l)},clearArtifacts(){Xt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return k&&!X&&!D()||!ue?!1:(ue.focus(),!0)},async resolveApproval(l,g,h){let A=_.getMessages().find(L=>L.variant==="approval"&&L.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){E(l)},on(l,g){return d.on(l,g)},off(l,g){d.off(l,g)},isOpen(){return $()&&X},isVoiceActive(){return Je.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:$()&&X,launcherEnabled:k,voiceActive:Je.active,streaming:_.isStreaming()}},showCSATFeedback(l){!X&&$()&&ut(!0,"system");let g=Le.querySelector(".persona-feedback-container");g&&g.remove();let h=Pc({onSubmit:async(x,A)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});Le.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!X&&$()&&ut(!0,"system");let g=Le.querySelector(".persona-feedback-container");g&&g.remove();let h=Lc({onSubmit:async(x,A)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});Le.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(){sl(),Bo!=null&&(clearInterval(Bo),Bo=null),qe.forEach(l=>l()),De.remove(),Ze?.remove(),Nt?.destroy(),Kt?.remove(),Po&&T.removeEventListener("click",Po)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:h=>h?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,qe.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=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",g),qe.push(()=>{window.removeEventListener("persona:focusInput",g)}),ce){let N=ie=>{let ge=ie.detail;(!ge?.instanceId||ge.instanceId===l)&&Lt.showEventStream()},G=ie=>{let ge=ie.detail;(!ge?.instanceId||ge.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",G),qe.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",G)})}let h=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.showArtifacts()},x=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.hideArtifacts()},A=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==l||G?.artifact&&Lt.upsertArtifact(G.artifact)},L=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==l||typeof G?.id=="string"&&Lt.selectArtifact(G.id)},J=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",J),qe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",J)})}let un=ow(o.persistState);if(un&&$()){let l=rw(un.storage),g=`${un.keyPrefix}widget-open`,h=`${un.keyPrefix}widget-voice`,x=`${un.keyPrefix}widget-voice-mode`;if(l){let A=un.persist?.openState&&l.getItem(g)==="true",L=un.persist?.voiceState&&l.getItem(h)==="true",J=un.persist?.voiceState&&l.getItem(x)==="true";if(A&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(L||J)Lt.startVoiceRecognition();else if(un.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),un.persist?.openState&&(d.on("widget:opened",()=>{l.setItem(g,"true")}),d.on("widget:closed",()=>{l.setItem(g,"false")})),un.persist?.voiceState&&(d.on("voice:state",N=>{l.setItem(h,N.active?"true":"false")}),d.on("user:message",N=>{l.setItem(x,N.viaVoice?"true":"false")})),un.clearOnChatClear){let N=()=>{l.removeItem(g),l.removeItem(h),l.removeItem(x)},G=()=>N();window.addEventListener("persona:clear-chat",G),qe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(f&&$()&&setTimeout(()=>{Lt.open()},0),lr(),!zg){let l=ls(()=>{_&&(Ki++,Lo.clear(),Xr(Le,_.getMessages(),re))});qe.push(l)}return Lt};var ng=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},iw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},lw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},cw=(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"},Dc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},rg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dc(e)},Wc=e=>{e.style.transition=""},Hc=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=""},Bc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Li=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},dw=(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))},pw=(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)},uw=e=>{let t=Go(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Gt(t,r)??r;return{inset:o(n?.inset,Va),canvasBackground:o(n?.canvasBackground,Ka)}},sg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},fw=(e,t,n,o,r,s,a,i)=>{let d=sn(s),p=d.reveal==="push",c=i!=null,u=i?.inset??"",b=i?.canvasBackground??"";dw(e,t,n,o,p),pw(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,E=f!=null?f.innerWidth<=C:!1;if(y&&E&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hc(t),Wc(o),rg(o),Bc(n),Li(r,o),sg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Vt),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"),rg(o),iw(o,d.maxHeight),sg(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",Hc(t),Wc(o),Bc(n),Li(r,o);let W=d.animate?"transform 180ms ease":"none",M=d.side==="right"?"translateX(100%)":"translateX(-100%)",k=a?"translateX(0)":M;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",Wc(o),Dc(o),Li(r,o);let W=ng(d.width,e.clientWidth),M=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=`${M+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=`${M}px`,n.style.maxWidth=`${M}px`,n.style.minWidth=`${M}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="",Hc(t),Dc(o),Bc(n),Li(r,o);let W=d.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let M=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 ${M}`,o.style.width=M,o.style.maxWidth=M,o.style.minWidth=M,o.style.minHeight="0",lw(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 z=c?`calc(${ng(d.width,e.clientWidth)}px - (2 * ${u}))`:d.width;r.style.width=z,r.style.minWidth=z,r.style.maxWidth=z,r.style.boxSizing="border-box"}}},gw=(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()}}},mw=(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?uw(t):null};C();let E=()=>{fw(a,i,d,p,c,t,u,y)},P=null,W=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=ks(()=>{C(),E()}))},M=()=>{f(),sn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{E()}),b.observe(a)))},k=!1,F=()=>{E(),M(),u&&!k&&a.dataset.personaDockMobileFullscreen!=="true"&&(k=!0,cw(a,sn(t)))},z=a.ownerDocument.defaultView,w=()=>{F()};return z?.addEventListener("resize",w),sn(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(U){let q=U.launcherEnabled?U.open:!0;u!==q&&(u=q,F())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),F(),W()},destroy(){z?.removeEventListener("resize",w),P?.(),P=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Ri=(e,t)=>Ht(t)?mw(e,t):gw(e,t);var hw=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},ag=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},ig=e=>{let t=hw(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Ri(t,r),a,i=[],d=(E,P)=>{let M=!(P?.launcher?.enabled??!0)||Ht(P),k=o.createElement("div");if(k.setAttribute("data-persona-root","true"),M&&(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),ag(F,o)}else E.appendChild(k),ag(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=Ic(E,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),e.onChatReady?.();let f=E=>{b(),s.destroy(),s=Ri(t,E),r=E,u()},y={update(E){let P=Ti(r??{},E),W=Ht(r),M=Ht(P),k=Co(r),F=Co(P);if(W!==M||k!==F){f(P);return}r=P,s.updateConfig(r),a.update(E),p()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(y,{get(E,P,W){if(P==="host")return s.host;if(P in E)return Reflect.get(E,P,W);let M=a[P];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function yw(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 bw(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:yw(o,n)?2:3}function lg(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Oc(e,t){let n=t.trim();if(!n)return[...e].sort(lg);let o=[];for(let r of e){let s=bw(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:lg(r.item,s.item)),o.map(r=>r.item)}function vw(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 xw(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Oc(e.items,t),resolve:e.resolve}}function Cw(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=>Oc(t,vw(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 fg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),ww=new Set(["button","a","input","select","textarea","details","summary"]),Aw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Nc=/\b(product|card|item|listing|result)\b/i,_c=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Sw=3e3,Tw=100;function gg(e){let t=typeof e.className=="string"?e.className:"";if(Nc.test(t)||e.id&&Nc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Nc.test(o.value))return!0}return!1}function mg(e){return _c.test((e.textContent??"").trim())}function hg(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 Mw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function cg(e){let t=e.match(_c);return t?t[0]:null}function dg(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 Ew(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 kw="commerce-card",Pw="result-card";function pg(e){return!gg(e)||!mg(e)||!hg(e)&&!Mw(e)?0:5200}function ug(e){return!gg(e)||mg(e)||!hg(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var yg=[{id:kw,scoreElement(e){return pg(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||_c.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(pg(e)===0)return null;let{title:n,href:o}=dg(e),r=cg((e.textContent??"").trim())??cg(t.text)??"",s=Ew(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
|
+
${At?"background: transparent !important;":""}
|
|
142
|
+
`}if(!v&&!l){let Pt="max-height: -moz-available !important; max-height: stretch !important;",tn=u?"":"padding-top: 1.25em !important;",Ga=u?"":`z-index: ${o.launcher?.zIndex??_t} !important;`;ke.style.cssText+=Pt+tn+Ga}bn()},Sl=()=>{e.style.setProperty("--persona-content-max-width",Eo(o,Q()))},lp=()=>{if(Q())return;let l=Mt(o),u=o.launcher?.sidebarMode??!1;if(l||u||(o.launcher?.fullHeight??!1)||!O)return;let v=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&v.innerWidth<=k)return;let j=v.innerHeight,N=64,q=o.launcher?.heightOffset??0,X=Math.max(200,j-N),ge=Math.min(640,X);ve.style.height=`${Math.max(200,ge-q)}px`};Al(),Gr(e,o),va(e,o),xa(e,o),Sl(),_o=()=>{Al(),lp(),Gr(e,o),va(e,o),xa(e,o),Sl(),Sa?e.style.setProperty("--persona-artifact-welded-outer-radius",Sa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Oe=[];Oe.push(()=>{document.removeEventListener("keydown",sp)}),Oe.push(()=>{gs!==null&&clearTimeout(gs)});let Wn=null,Hn=null;Oe.push(()=>{Wn?.(),Wn=null,Hn?.(),Hn=null}),hs&&Oe.push(()=>{hs?.disconnect(),hs=null}),Oe.push(()=>{vs?.(),vs=null,wl(),Ct&&(Ct.remove(),Ct=null),Je?.element.style.removeProperty("width"),Je?.element.style.removeProperty("maxWidth")}),fe&&Oe.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),we?.destroy(),we=null,Le?.destroy(),Le=null,$e=null});let jo=null,cp=()=>{jo&&(jo(),jo=null),o.colorScheme==="auto"&&(jo=na(()=>{Gr(e,o)}))};cp(),Oe.push(()=>{jo&&(jo(),jo=null)}),Oe.push(d);let Ra=o.features?.streamAnimation;if(Ra?.type&&Ra.type!=="none"){let l=Qr(Ra.type,Ra.plugins);l&&(Wi(l,e),Oe.push(()=>wf(e)))}let qn=ua(E),dp=ua(Sn),pp=ua(ne),Uo=[qn,dp,pp];Oe.push(()=>{Uo.forEach(l=>l.destroy())});let zo=null,F,qo=null,up=!1,gp=0,fp=null,mp=l=>l.reduce((u,m)=>m.role==="user"?u+1:u,0),hp=l=>{for(let u=l.length-1;u>=0;u--)if(Ur(l[u]))return l[u].id??null;return null},yp=!1,vh=()=>{yp||o.debug!==!0||(yp=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},bp=!1,vp=!1,xp=(l,u)=>{bp||o.debug!==!0||!u.enabled||u.expose||up||vp&&(F.isStreaming()||l.some(Ur)||(bp=!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.")))},Tr=l=>{if(!F)return;let u=l??F.getMessages(),m=X=>{X.render([],F,I,u)},v=X=>{Uo.forEach(ge=>{ge!==X&&m(ge)})};qo&&(mp(u)>gp||hp(u)!==fp)&&(qo=null);let w=Ao(o);xp(u,w);let k=w.enabled?mc(u):null,j=qo??k,N=qo?"host":"agent";if(j){let X=o.suggestions?.followUps,ge=X?.placement??(X?"auto":"composer"),xe=(ge==="auto"?Q()?"composer":"after-message":ge)==="after-message"?pp:qn;v(xe),xe.render(j,F,I,u,o.suggestionChipsConfig,{source:N,surface:"followUp",variant:X?.variant??"chip",behavior:X?.behavior??"send",overflow:X?.overflow??"wrap",maxItems:X?.maxItems??4,config:o,plugins:s});return}if(u.some(X=>X.role==="user")){Uo.forEach(m);return}let q=o.suggestions?.starters;if(q){let X=hr(Bo(o),u),ge=q.placement??"auto",ce=ge==="auto"?X?"welcome":"composer":ge;if(ce==="welcome"&&!X){vh(),Uo.forEach(m);return}let xe=ce==="welcome"?dp:qn;v(xe),xe.render(q.items??o.suggestionChips,F,I,u,o.suggestionChipsConfig,{surface:"starter",variant:q.variant??"card",behavior:q.behavior??"send",overflow:q.overflow??"wrap",maxItems:q.maxItems??4,config:o,plugins:s});return}v(qn),qn.render(o.suggestionChips,F,I,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},Cp=()=>{qo&&(qo=null,Tr())},xh=l=>{let u=Array.isArray(l)?[...l]:[];if(!u.length){Cp();return}let m=F?F.getMessages():[];qo=u,up=!0,gp=mp(m),fp=hp(m),Tr(m)},kn=!1,Vo=gf(),Er=new Map,Ko=new Map,lo=new Map,Tl=0,Ch=Zn()!==null,on=Mi(),rn=0,co=null,Zt=!1,Ia=!1,po=0,Dt=null,Go=null,El=!1,Wa=!1,Jo=null,xs=!0,Ha=!1,Mr=null,Ba=!1,Yo=()=>{Ba=!0,Th()},Ml=null,wh=4,Vn=24,Ah=80,Sh=1e3,Kn=null,wp=()=>{e.setAttribute("data-persona-scrollbar",gl()),gl()!=="on-scroll"&&(Kn!==null&&clearTimeout(Kn),Kn=null,re.removeAttribute("data-persona-scrollbar-visible"))},Th=()=>{gl()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Kn!==null&&clearTimeout(Kn),Kn=setTimeout(()=>{Kn=null,oo(re,Vn)&&re.removeAttribute("data-persona-scrollbar-visible")},Sh))};wp(),Oe.push(()=>{Kn!==null&&clearTimeout(Kn)});let kl=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ap=o.voiceRecognition?.autoResume??!1,Gn=l=>{c.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},Ln=()=>{P(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Eh=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=Ed(f.voiceState),u=!!l.active,m=Number(l.timestamp??0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-m<iS&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?F.toggleVoice().then(()=>{Ke.active=F.isVoiceActive(),Gn("restore"),F.isVoiceActive()&&Wr()}):za("restore"))},1e3)},Mh=()=>F?Mm(F.getMessages()).filter(l=>!l.__skipPersist):[],Da=null,Sp=(l,u)=>{typeof console<"u"&&console.error(l,u)},Ll=(l,u)=>{let m=()=>{try{let j=l();return!j||typeof j.then!="function"?null:Promise.resolve(j).catch(N=>{Sp(u,N)})}catch(j){return Sp(u,j),null}},v=Da,w=v?v.then(()=>m()??void 0):m();if(!w)return;let k=w.finally(()=>{Da===k&&(Da=null)});Da=k};function Pl(l){if(!b?.save)return;let m={messages:l?Mm(l):F?Mh():[],metadata:f,artifacts:En.artifacts,selectedArtifactId:En.selectedId};Ll(()=>b.save(m),"[AgentWidget] Failed to persist state:")}let kr=null,Tp=()=>ke.querySelector("#persona-scroll-container")||re,Lr=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Zt=!1},Ep=()=>{co!==null&&(cancelAnimationFrame(co),co=null),Ia=!1,Lr()},kh=()=>kn&&Il()&&(nn()!=="anchor-top"||_d()),Rl=()=>{let l=ds()||"Jump to latest",u=kh();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),po>0?(Oo.textContent=String(po),Oo.style.display="",Rt.setAttribute("aria-label",`${l} (${po} new)`)):(Oo.textContent="",Oo.style.display="none",Rt.setAttribute("aria-label",u?`${l} (response streaming below)`:l))},Mp=()=>{po!==0&&(po=0,Rl())},Lh=()=>{let l=Dt?.spacerHeight??0;return l<=0?oo(re,Vn):Fa(l)-re.scrollTop-re.clientHeight<=Vn},Il=()=>ao()?!on.isFollowing():!Lh(),Wl=()=>!!F&&F.getMessages().length>0,jt=()=>{if(!gh()||ae){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==Ce&&Ce.appendChild(Rt),Fo();let u=_n(re)>0&&Il()&&Wl();u?Rl():Mp(),Rt.style.display=u?"":"none"},Cs=()=>{on.pause()&&(Ep(),jt())},uo=()=>{on.resume(),Mp(),jt()},go=(l=!1)=>{ao()&&Wl()&&on.isFollowing()&&(!l&&!kn||(co!==null&&(cancelAnimationFrame(co),co=null),Ia=!0,co=requestAnimationFrame(()=>{co=null,Ia=!1,on.isFollowing()&&Ph(Tp(),l?220:140)})))},kp=(l,u,m,v=()=>!0)=>{let w=l.scrollTop,k=u(),j=k-w;if(Lr(),Math.abs(j)<1){Zt=!0,l.scrollTop=k,rn=l.scrollTop,Zt=!1;return}let N=performance.now();Zt=!0;let q=ge=>1-Math.pow(1-ge,3),X=ge=>{if(!v()){Lr();return}let ce=u();ce!==k&&(k=ce,j=k-w);let xe=ge-N,Ge=Math.min(xe/m,1),yt=q(Ge),ut=w+j*yt;l.scrollTop=ut,rn=l.scrollTop,Ge<1?kr=requestAnimationFrame(X):(l.scrollTop=k,rn=l.scrollTop,kr=null,Zt=!1)};kr=requestAnimationFrame(X)},Ph=(l,u=500)=>{let m=_n(l)-l.scrollTop;if(Math.abs(m)<1){rn=l.scrollTop;return}if(Math.abs(m)>=Ah){Lr(),Zt=!0,l.scrollTop=_n(l),rn=l.scrollTop,Zt=!1;return}kp(l,()=>_n(l),u,()=>on.isFollowing())},Lp=()=>{if(!Wl()){jt();return}let l=Tp();Zt=!0,l.scrollTop=_n(l),rn=l.scrollTop,Zt=!1,jt()},Xo=l=>{let u=0,m=l;for(;m&&m!==re;)u+=m.offsetTop,m=m.offsetParent;return u},Rh=()=>{let l=re.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??re.ownerDocument.getSelection()},Oa=()=>bf(Rh(),re),Pp=()=>{if(fh()!=="last-user-turn")return!1;let l=F?.getMessages()??[];if(l.length<2)return!1;let u=[...l].reverse().find(k=>k.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=re.querySelector(`[data-message-id="${m}"]`);if(!v)return!1;let w=Math.min(Math.max(0,Xo(v)-ps()),_n(re));return Zt=!0,re.scrollTop=w,rn=re.scrollTop,Zt=!1,nn()==="follow"&&!oo(re,Vn)&&on.pause(),jt(),!0},Na=l=>{let u=Math.max(0,Math.round(l));mn.style.height=`${u}px`,mn.style.display=u>0?"":"none",Dt&&(Dt.spacerHeight=Math.max(0,l))},Fa=l=>{let u=parseFloat(getComputedStyle(re).paddingBottom)||0,m=0;for(let w of Array.from(re.children)){if(w===mn||w.offsetHeight===0)continue;let k=Xo(w)+w.offsetHeight;k>m&&(m=k)}let v=re.scrollHeight-l;return m>0?Math.min(m+u,v):v},Ih=()=>{if(!Dt||Dt.spacerHeight<=0)return;let l=Fa(Dt.spacerHeight),u=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-l+Vn);u<Dt.spacerHeight&&(Na(u),jt())},ws=()=>{Go!==null&&(cancelAnimationFrame(Go),Go=null),Lr(),Dt=null,mn.style.height="0px",mn.style.display="none"},Rp=l=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Hl=l=>re.querySelector(`[data-message-id="${Rp(l)}"]`),Ip=l=>{Go!==null&&cancelAnimationFrame(Go),Go=requestAnimationFrame(()=>{Go=null;let u=Rp(l),m=re.querySelector(`[data-message-id="${u}"]`);if(!m)return;let v=Xo(m),w=Dt?.spacerHeight??0,k=Fa(w),{targetScrollTop:j,spacerHeight:N}=zc({anchorOffsetTop:v,topOffset:ps(),viewportHeight:re.clientHeight,contentHeight:k,slack:Vn});Dt={initialSpacerHeight:N,contentHeightAtAnchor:k,spacerHeight:N},Na(N),kp(re,()=>m.isConnected?Math.max(0,Xo(m)-ps()):j,220)})},Wp=()=>{if(nn()!=="anchor-top"||!Dt||!Mr)return;let l=Hl(Mr);if(!l)return;Lr();let u=Dt.spacerHeight,m=Fa(u),{targetScrollTop:v,spacerHeight:w}=zc({anchorOffsetTop:Xo(l),topOffset:ps(),viewportHeight:re.clientHeight,contentHeight:m,slack:Vn});Dt={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Na(w),Zt=!0,re.scrollTop=v,rn=re.scrollTop,Zt=!1,jt()},Wh=()=>{if(ao()){if(!on.isFollowing()||oo(re,1))return;go(!kn);return}if(Dt&&Dt.initialSpacerHeight>0){let l=re.scrollHeight-Dt.spacerHeight,u=vf({initialSpacerHeight:Dt.initialSpacerHeight,contentHeightAtAnchor:Dt.contentHeightAtAnchor,currentContentHeight:l});u!==Dt.spacerHeight&&Na(u)}jt()},Hh=l=>{let u=nn();u==="follow"?(uo(),go(!0)):u==="anchor-top"&&(xs=!1,Ha=!0,Ba=!1,Mr=l,Ip(l))},Bh=()=>{if(nn()==="anchor-top"){if(Ha){xs=!1;return}xs=!0,ws(),uo(),go(!0)}},Dh=96,Oh=l=>{if(Jo===null)return!0;let u=Hl(Jo),m=Hl(l);if(!u||!m)return!0;let v=Xo(m)-Xo(u);return ps()+v>re.clientHeight-Dh},Nh=l=>{if(nn()!=="anchor-top"||!Ha||Ba||Oa())return;let u=Jo===null;for(let m of l){if(!u){m.id===Jo&&(u=!0);continue}if(yf(m)){if(m.id===Mr||!Oh(m.id))return;Mr=m.id,Ip(m.id);return}}},Fh=l=>{let u=new Map;l.forEach(m=>{let v=kl.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!v&&m.role==="assistant"&&(c.emit("assistant:message",m),!Wa&&(nn()!=="anchor-top"||_d())&&Il()&&(po+=1,Rl(),jt(),jd(po===1?"1 new message below.":`${po} new messages below.`))),m.role==="assistant"&&v?.streaming&&m.streaming===!1&&c.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(v?m.approval.status!=="pending"&&c.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):c.emit("approval:requested",{approval:m.approval,message:m}))}),kl.clear(),u.forEach((m,v)=>{kl.set(v,m)})},_a=(l,u)=>{let m=u==="user"?"user":"assistant",v=o.layout?.messages?.[m],w=v?.width??"content",k=v?.maxWidth??(w==="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-${u}`,`persona-message-width-${w}`),l.classList.toggle("persona-justify-end",u==="user"),l.setAttribute("data-message-role",u),l.setAttribute("data-message-width",w),l.style.setProperty("--persona-message-row-max-width",k)},Qo=(l,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${l}`,m.setAttribute("data-wrapper-id",l),_a(m,u),m},_h=(l,u,m)=>{let v=document.createElement("div"),k=(()=>{let D=s.find(Ie=>Ie.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),j=(D,Ie)=>Ie==null?!1:typeof Ie=="string"?(D.textContent=Ie,!0):(D.appendChild(Ie),!0),N=new Set,q=new Map,X=new Set,ge=s.some(D=>D.renderAskUserQuestion),ce=[],xe=[],Ge=o.enableComponentStreaming!==!1,yt=o.approval!==!1,ut=[];if(u.forEach(D=>{N.add(D.id),q.set(D.id,D.role);let Ie=ge&&vo(D),Ne=yt&&D.variant==="approval"&&!!D.approval,Ee=!Ie&&D.role==="assistant"&&!D.variant&&Ge&&nl(D);!Ne&&lo.has(D.id)&&(l.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),lo.delete(D.id)),!Ee&&Ko.has(D.id)&&(l.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Ko.delete(D.id));let Tt=vo(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",gt=uf(D,Tl)+Tt,Nt=Ie||Ne||Ee?null:ff(Vo,D.id,gt);if(Nt){v.appendChild(Nt.cloneNode(!0)),vo(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),Us(D,o,Te.composerOverlay));return}let ft=null,en=s.find(Fe=>!!(D.variant==="reasoning"&&Fe.renderReasoning||D.variant==="tool"&&Fe.renderToolCall||!D.variant&&Fe.renderMessage)),Ht=o.layout?.messages;if(vo(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){Er.delete(D.id),l.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ur(D)&&Ao(o).enabled)return;if(vo(D)&&o.features?.askUserQuestion?.enabled!==!1){let Fe=s.find(Ut=>typeof Ut.renderAskUserQuestion=="function");if(Fe&&at.current){let Ut=Er.get(D.id),zt=Ut!==gt,At=null;if(zt){let{payload:Ye,complete:De}=xo(D),bt=D.id,qt=()=>at.current?.getMessages().find(bn=>bn.id===bt);At=Fe.renderAskUserQuestion({message:D,payload:Ye,complete:De,resolve:bn=>{let Ws=qt();Ws&&at.current?.resolveAskUserQuestion(Ws,bn)},dismiss:()=>{let bn=qt();bn?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(bn),at.current?.resolveAskUserQuestion(bn,"(dismissed)"))},config:o})}let it=Ut!=null;if(zt&&At===null&&!it){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),Us(D,o,Te.composerOverlay));return}let mt=Qo(D.id,D.role);mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),v.appendChild(mt),ce.push({messageId:D.id,fingerprint:gt,bubble:At});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),Us(D,o,Te.composerOverlay));return}}else if(Ne){let Fe=s.find(it=>typeof it.renderApproval=="function")??p,zt=lo.get(D.id)!==gt,At=null;if(zt&&Fe?.renderApproval){let it=D.id,mt=(Ye,De)=>{let bt=at.current?.getMessages().find(qt=>qt.id===it);bt?.approval&&(bt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(bt.id,Ye):at.current?.resolveApproval(bt.approval,Ye,De))};At=Fe.renderApproval({message:D,defaultRenderer:()=>Ki(D,o),config:o,approve:Ye=>mt("approved",Ye),deny:Ye=>mt("denied",Ye)})}if(zt&&At===null)l.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),lo.delete(D.id),ft=Ki(D,o);else{let it=Qo(D.id,D.role);it.setAttribute("data-approval-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),v.appendChild(it),ut.push({messageId:D.id,fingerprint:gt,bubble:At});return}}else if(en)if(D.variant==="reasoning"&&D.reasoning&&en.renderReasoning){if(!ue)return;ft=en.renderReasoning({message:D,defaultRenderer:()=>ad(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&en.renderToolCall){if(!te)return;ft=en.renderToolCall({message:D,defaultRenderer:()=>ld(D,o),config:o})}else en.renderMessage&&(ft=en.renderMessage({message:D,defaultRenderer:()=>{let Fe=ma(D,m,Ht,o.messageActions,et,{loadingIndicatorRenderer:k,widgetConfig:o});return D.role!=="user"&&yd(Fe,D,o,F),Fe},config:o}));if(!ft&&Ee){let Fe=Ad(D);if(Fe){let Ut=Ko.get(D.id),zt=Ut!==gt,At=o.wrapComponentDirectiveInBubble!==!1&&Fn.getOptions(Fe.component)?.bubbleChrome!==!1,it=null;if(zt){let mt=wd(Fe,{config:o,message:D,transform:m});if(mt&&Fe.component==="PersonaArtifactInline"){let Ye=mt.hasAttribute("data-artifact-inline")?mt:mt.querySelector("[data-artifact-inline]"),De=Ye?.getAttribute("data-artifact-inline")??"",bt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,qt=De?l.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${bt}"]`)??null:null;Ye&&qt&&qt!==Ye&&af(qt)&&(Ye===mt?mt=qt:Ye.replaceWith(qt))}if(mt)if(At){let Ye=document.createElement("div");if(Ye.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ye.id=`bubble-${D.id}`,Ye.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let De=document.createElement("div");De.className="persona-mb-3 persona-text-sm persona-leading-relaxed",De.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ye.appendChild(De)}Ye.appendChild(mt),it=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${D.id}`,Ye.setAttribute("data-message-id",D.id),Ye.setAttribute("data-persona-component-directive","true"),D.content&&D.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:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ye.appendChild(De)}Ye.appendChild(mt),it=Ye}}if(it||Ut!=null){let mt=Qo(D.id,D.role);mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),v.appendChild(mt),xe.push({messageId:D.id,fingerprint:gt,bubble:it});return}}}if(!ft)if(D.variant==="reasoning"&&D.reasoning){if(!ue)return;ft=ad(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!te)return;ft=ld(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;ft=Ki(D,o)}else{let Fe=o.layout?.messages;Fe?.renderUserMessage&&D.role==="user"?ft=Fe.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):Fe?.renderAssistantMessage&&D.role==="assistant"?ft=Fe.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):ft=ma(D,m,Fe,o.messageActions,et,{loadingIndicatorRenderer:k,widgetConfig:o}),D.role!=="user"&&ft&&yd(ft,D,o,F)}let We=Qo(D.id,D.role);We.appendChild(ft),mf(Vo,D.id,gt,We),v.appendChild(We)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let Ne=Ie.getAttribute("data-persona-ask-sheet-for");Ne&&!X.has(Ne)&&ar(Te.composerOverlay,Ne)}),o.features?.toolCallDisplay?.grouped){let D=[],Ie=[],Ne=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(Ee=>{if(Ee.variant==="tool"&&Ee.toolCall&&te){Ie.push(Ee);return}Ee.variant==="reasoning"&&!ue||((Ie.length>1||Ne&&Ie.length>0)&&D.push(Ie),Ie=[])}),(Ie.length>1||Ne&&Ie.length>0)&&D.push(Ie),D.forEach(Ee=>{let Tt=Ee.map(Fe=>Array.from(v.children).find(Ut=>Ut instanceof HTMLElement&&Ut.getAttribute("data-wrapper-id")===Fe.id)).filter(Fe=>!!Fe);if(Tt.length<(Ne?1:2))return;let gt=Qo(`tool-group-${Ee[0].id}`,"assistant");gt.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 ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Ee[0].id}`;let en=`Called ${Ee.length} ${Ee.length===1?"tool":"tools"}`,Ht=o.toolCall?.renderGroupedSummary?.({messages:Ee,toolCalls:Ee.map(Fe=>Fe.toolCall).filter(Fe=>!!Fe),defaultSummary:en,config:o});j(ft,Ht)||(ft.textContent=en);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Ee[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),Nt.appendChild(ft),Ne||Nt.appendChild(We),gt.appendChild(Nt),Tt[0].before(gt),Tt.forEach((Fe,Ut)=>{if(Ne){Fe.remove();return}Fe.style.setProperty("--persona-message-row-max-width","100%");let zt=document.createElement("div");zt.className="persona-tool-group-item persona-relative",zt.setAttribute("data-persona-tool-group-item","true"),Ut<Tt.length-1&&zt.setAttribute("data-persona-tool-group-connector","true"),zt.appendChild(Fe),We.appendChild(zt)})})}hf(Vo,N);let sn=u.some(D=>D.role==="assistant"&&D.streaming),Et=u[u.length-1],Wt=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(kn&&u.some(D=>D.role==="user")&&!sn&&!Wt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:ts},Ie=s.find(Ee=>Ee.renderLoadingIndicator),Ne=null;if(Ie?.renderLoadingIndicator&&(Ne=Ie.renderLoadingIndicator(D)),Ne===null&&o.loadingIndicator?.render&&(Ne=o.loadingIndicator.render(D)),Ne===null&&(Ne=ts()),Ne){let Ee=document.createElement("div"),Tt=o.loadingIndicator?.showBubble!==!1,gt=o.layout?.messages?.layout??"bubble";Ee.className=Tt?fa("assistant",gt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ee.setAttribute("data-typing-indicator","true"),Tt&&(Ee.style.color="var(--persona-message-assistant-text, var(--persona-text))",gt!=="flat"&&(Ee.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ee.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ee.appendChild(Ne);let Nt=Qo("typing-indicator","assistant");Nt.appendChild(Ee),v.appendChild(Nt)}}if(!kn&&u.length>0){let D=u[u.length-1],Ie={config:o,lastMessage:D,messageCount:u.length},Ne=s.find(Tt=>Tt.renderIdleIndicator),Ee=null;if(Ne?.renderIdleIndicator&&(Ee=Ne.renderIdleIndicator(Ie)),Ee===null&&o.loadingIndicator?.renderIdle&&(Ee=o.loadingIndicator.renderIdle(Ie)),Ee){let Tt=document.createElement("div"),gt=o.loadingIndicator?.showBubble!==!1;Tt.className=gt?["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(" "),Tt.setAttribute("data-idle-indicator","true"),Tt.appendChild(Ee);let Nt=Qo("idle-indicator","assistant");Nt.appendChild(Tt),v.appendChild(Nt)}}if(Bu(v),Ei(l,v),sc(l),ce.length>0)for(let{messageId:D,fingerprint:Ie,bubble:Ne}of ce){let Ee=l.querySelector(`#wrapper-${D}`);Ee&&(_a(Ee,q.get(D)??"assistant"),Ne!==null&&(Ee.replaceChildren(Ne),Ee.setAttribute("data-bubble-fp",Ie),Er.set(D,Ie)))}if(Er.size>0)for(let D of Er.keys())N.has(D)||Er.delete(D);if(xe.length>0)for(let{messageId:D,fingerprint:Ie,bubble:Ne}of xe){let Ee=l.querySelector(`#wrapper-${D}`);Ee&&(_a(Ee,q.get(D)??"assistant"),Ne!==null&&(Ee.replaceChildren(Ne),Ee.setAttribute("data-bubble-fp",Ie),Ko.set(D,Ie)))}if(Ko.size>0)for(let D of Ko.keys())N.has(D)||Ko.delete(D);if(ut.length>0)for(let{messageId:D,fingerprint:Ie,bubble:Ne}of ut){let Ee=l.querySelector(`#wrapper-${D}`);Ee&&(_a(Ee,q.get(D)??"assistant"),Ne!==null&&(Ee.replaceChildren(Ne),Ee.setAttribute("data-bubble-fp",Ie),lo.set(D,Ie)))}if(lo.size>0)for(let D of lo.keys())N.has(D)||lo.delete(D)},As=(l,u,m)=>{_h(l,u,m),np()},Ss=null,$h=()=>{if(Ss)return;let l=m=>{let v=m.composedPath();v.includes(ke)||tt&&v.includes(tt)||pt(!1,"user")};Ss=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Hp=()=>{if(!Ss)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ss,!0),Ss=null};Oe.push(()=>Hp());let Ts=null,jh=()=>{if(Ts)return;let l=m=>{m.key==="Escape"&&(m.isComposing||pt(!1,"user"))};Ts=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Bp=()=>{if(!Ts)return;(e.ownerDocument??document).removeEventListener("keydown",Ts,!0),Ts=null};Oe.push(()=>Bp());let Es=!1,Dp=new Set,Uh=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},Pr=()=>{if(!Q())return;let l=Te.peekBanner,u=Te.peekTextNode;if(!l||!u)return;if(J){l.classList.remove("persona-pill-peek--visible");return}let m=F?.getMessages()??[],v;for(let Et=m.length-1;Et>=0;Et--){let Wt=m[Et];if(Wt.role==="assistant"&&Wt.content){v=Wt;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let w=v.content,k=!!v.streaming,j=Uh(),N=Pi(j),q=N.type!=="none"?Qr(N.type,j?.plugins):null,X=q?.isAnimating?.(v)===!0,ge=q!==null&&(k||X);ge&&q&&!Dp.has(q.name)&&(Wi(q,e),Dp.add(q.name));let ce=ge&&q?.containerClass?q.containerClass:null,xe=u.dataset.personaPeekStreamClass??null;xe&&xe!==ce&&(u.classList.remove(xe),delete u.dataset.personaPeekStreamClass),ce&&xe!==ce&&(u.classList.add(ce),u.dataset.personaPeekStreamClass=ce),ge?(u.style.setProperty("--persona-stream-step",`${N.speed}ms`),u.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Ge=ge?Ri(w,N.buffer,q,v,k):w;if(ge&&N.placeholder==="skeleton"&&k&&(!Ge||!Ge.trim())){let Et=document.createElement("div"),Wt=ca();Wt.classList.add("persona-pill-peek__skeleton"),Et.appendChild(Wt),Ei(u,Et)}else{let Et=Math.max(0,Ge.length-100),Wt=Ge.length>100?Ge.slice(-100):Ge,D=eo(Wt);if(!ge||!q){let Ie=Ge.length>100?`\u2026${Wt}`:Wt;u.textContent!==Ie&&(u.textContent=Ie)}else{let Ie=D;(q.wrap==="char"||q.wrap==="word")&&(Ie=la(D,q.wrap,`peek-${v.id}`,{skipTags:q.skipTags,startIndex:Et}));let Ne=document.createElement("div");if(Ne.innerHTML=Ie,q.useCaret&&Wt.length>0){let Ee=Ii(),Tt=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),gt=Tt[Tt.length-1];gt?.parentNode?gt.parentNode.insertBefore(Ee,gt.nextSibling):Ne.appendChild(Ee)}Ei(u,Ne),q.onAfterRender?.({container:u,bubble:l,messageId:v.id,message:v,speed:N.speed,duration:N.duration})}}let sn=kn||Es;l.classList.toggle("persona-pill-peek--visible",sn)};if(Q()){let l=Te.peekBanner;if(l){let v=w=>{w.preventDefault(),w.stopPropagation(),pt(!0,"user")};l.addEventListener("pointerdown",v),Oe.push(()=>{l.removeEventListener("pointerdown",v)})}let u=()=>{Es||(Es=!0,Pr())},m=()=>{Es&&(Es=!1,Pr())};ve.addEventListener("pointerenter",u),ve.addEventListener("pointerleave",m),Oe.push(()=>{ve.removeEventListener("pointerenter",u),ve.removeEventListener("pointerleave",m)}),tt&&(tt.addEventListener("pointerenter",u),tt.addEventListener("pointerleave",m),Oe.push(()=>{tt.removeEventListener("pointerenter",u),tt.removeEventListener("pointerleave",m)}))}let zh=l=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",v=u.bottomOffset??"16px",w=u.collapsedMaxWidth,k=u.expandedMaxWidth??"880px",j=u.expandedTopOffset??"5vh",N=u.modalMaxWidth??"880px",q=u.modalMaxHeight??"min(90vh, 800px)",X="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ce=ke.style;if(ce.left="",ce.right="",ce.top="",ce.bottom="",ce.transform="",ce.width="",ce.maxWidth="",ce.height="",ce.maxHeight="",tt){let xe=tt.style;xe.bottom=v,xe.width=w??""}if(l&&m!=="fullscreen"){if(m==="modal"){ce.top="50%",ce.left="50%",ce.transform="translate(-50%, -50%)",ce.bottom="auto",ce.right="auto",ce.width=N,ce.maxWidth=X,ce.maxHeight=q,ce.height=q;return}ce.left="50%",ce.transform="translateX(-50%)",ce.bottom=`calc(${v} + ${ge})`,ce.top=j,ce.width=k,ce.maxWidth=X}},Ms=()=>{if(!le())return;if(Q()){let X=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=J?"expanded":"collapsed";ke.dataset.state=ge,ke.dataset.expandedSize=X,tt&&(tt.dataset.state=ge,tt.dataset.expandedSize=X),ke.style.removeProperty("display"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ve.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),zh(J),Ce.style.display=J?"flex":"none",_o(),J?($h(),jh()):(Hp(),Bp()),Pr();return}let l=Mt(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,k=v&&w&&O,j=cn(o).reveal;J?(ke.style.removeProperty("display"),ke.style.display=l?"flex":"",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ve.classList.remove("persona-scale-95","persona-opacity-0"),ve.classList.add("persona-scale-100","persona-opacity-100"),Lt?(Lt.setPanelOpen(!0),Lt.element.style.display="none"):Yt&&(Yt.style.display="none")):(l?l&&(j==="overlay"||j==="push")&&!k?(ke.style.removeProperty("display"),ke.style.display="flex",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ve.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.setProperty("display","none","important"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),ve.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.display="",ke.classList.add("persona-pointer-events-none","persona-opacity-0"),ve.classList.remove("persona-scale-100","persona-opacity-100"),ve.classList.add("persona-scale-95","persona-opacity-0")),Lt?(Lt.setPanelOpen(!1),Lt.element.style.display=l?"none":""):Yt&&(Yt.style.display=l?"none":""))},pt=(l,u="user")=>{if(!le()||J===l)return;let m=J;J=l,Ms();let v=(()=>{let k=o.launcher?.sidebarMode??!1,j=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,X=j.innerWidth<=q,ge=Mt(o)&&N&&X,ce=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||N&&X&&O||ge||ce})();if(J&&v){if(!Wn){let k=e.getRootNode(),j=k instanceof ShadowRoot?k.host:e.closest(".persona-host");j&&(Wn=Kc(j,o.launcher?.zIndex??_t))}Hn||(Hn=Gc(e.ownerDocument))}else J||(Wn?.(),Wn=null,Hn?.(),Hn=null);J&&(Rs(),Pp()||(nn()==="follow"?go(!0):Lp()));let w={open:J,source:u,timestamp:Date.now()};J&&!m?c.emit("widget:opened",w):!J&&m&&c.emit("widget:closed",w),c.emit("widget:state",{open:J,launcherEnabled:O,voiceActive:Ke.active,streaming:F.isStreaming()})},$a=l=>{wa(l?"stop":"send"),oe&&(oe.disabled=l),Uo.forEach(u=>{u.elements.forEach(m=>{m.toggleAttribute("data-disabled",l),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",l?"true":"false")}),u.buttons.forEach(m=>{m.disabled=l})}),Fl.forEach(u=>{u.toggleAttribute("data-disabled",l),u instanceof HTMLButtonElement?u.disabled=l:u.setAttribute("aria-disabled",l?"true":"false"),u.querySelectorAll("button").forEach(m=>{m.disabled=l})}),Se.dataset.personaComposerStreaming=l?"true":"false",Se.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},Bl=()=>{Ke.active||I&&I.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Bl(),200)});let Dl=!V.hidden,fo=null,Op=!x,Np=null,Fp,_p=null,ks=null,Ol=l=>{let u=Bo(o),m=`${u.variant}|${u.dismiss}|${u.title}|${u.subtitle}`;(m!==Np||u.icon!==Fp)&&(Np=m,Fp=u.icon,zi({host:V,iconHolder:$,title:de,subtitle:Ue,starterSuggestions:Sn},u));let v=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;v!==_p&&(_p=v,qi(K,u.message,o));let w=l??(F?F.getMessages():o.initialMessages),k=hr(u,w),j=k!==Dl;if(Dl=k,ks){fo?.cancel(),fo=null,ns(re,V,!0);return}if(j&&!k&&u.dismiss==="on-first-message"&&Op){fo=Ff(V,N=>{fo===N&&(fo=null),!Dl&&!ks&&(ns(re,V,!1),Wp()),N?.cancel()});return}if(fo){if(!k)return;fo.cancel(),fo=null}ns(re,V,k),j&&!k&&Wp()},Nl=[],Fl=[],_l=!1,$p=null,jp,Up=()=>{Fl.length=0;let l=Nl.splice(0,Nl.length);for(let u of l)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Oe.push(Up);let qh=(l,u)=>{let m=Yc(l,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),y("span");let v=o.suggestions?.starters,w=Xc({item:{...m,behavior:m.behavior??v?.behavior??"send"},index:u,surface:"starter",source:"config",variant:v?.variant??"card",streaming:a?F.isStreaming():!1,config:o,plugins:s,chipsConfig:o.suggestionChipsConfig,session:F,getTextarea:()=>I,eventTarget:V});return Fl.push(w),w},$l=()=>{if(_l)return;_l=!0;let l=Bo(o);$p=`${l.variant}|${l.dismiss}|${l.title}|${l.subtitle}|${l.message??""}`,jp=l.icon;try{Up(),Of(re,V,ks),ks=null;let u=F?F.getMessages():o.initialMessages,m=hr(l,u),v=0,w=null;for(let k of s)if(k.renderWelcome&&(w=k.renderWelcome({config:l,variant:l.variant,visible:m,defaultRenderer:()=>V,sendMessage:j=>{if(!F||F.isStreaming())return;let N=j.trim();N&&F.sendMessage(N)},requestRender:()=>$l(),renderStarter:j=>qh(j,v++),storage:i(k.id),onCleanup:j=>{Nl.push(j)}}),w))break;w&&w!==V&&(ks=w,Df(re,V,w))}finally{_l=!1}Ol()},Vh=()=>{let l=Bo(o);`${l.variant}|${l.dismiss}|${l.title}|${l.subtitle}|${l.message??""}`===$p&&l.icon===jp||$l()},jl=()=>{Ol(),yl||(I.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!F?.isStreaming()&&(h.textContent=o.copy?.sendButtonLabel??"Send")),I.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',I.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=f.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{P(u=>({...u,sessionId:l}))}});let Zo=null,Kh=()=>{Zo==null&&(Zo=setInterval(()=>{let l=Ae.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Zo),Zo=null;return}let u=Date.now();l.forEach(m=>{let v=Number(m.getAttribute("data-tool-elapsed"));v&&(m.textContent=si(u-v))})},100))},Ul=(l,u)=>{if(Object.is(l,u))return!0;if(l===null||u===null||typeof l!="object"||typeof u!="object")return!1;if(Array.isArray(l)||Array.isArray(u))return!Array.isArray(l)||!Array.isArray(u)||l.length!==u.length?!1:l.every((j,N)=>Ul(j,u[N]));let m=l,v=u,w=Object.keys(m),k=Object.keys(v);return w.length===k.length&&w.every(j=>Object.prototype.hasOwnProperty.call(v,j)&&Ul(m[j],v[j]))},zp=l=>{let{content:u,rawContent:m,llmContent:v,...w}=l;return w},zl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!nl(l),Gh=(l,u,m)=>{if(l.length!==u.length)return!1;let v=l[m.index],w=u[m.index];return!v||!w||v.id!==m.id||w.id!==m.id?!1:(!Object.is(v.content,w.content)||!Object.is(v.rawContent,w.rawContent)||!Object.is(v.llmContent,w.llmContent))&&zl(v)&&zl(w)&&Ul(zp(v),zp(w))},qp=null,Rr=null,er=null,Jn=null,ja=l=>{qp=l;let u,m;Rr=null;for(let w=l.length-1;w>=0;w-=1){let k=l[w];if(!u&&k.role==="user"&&(u=k),!m&&k.role==="assistant"&&(m=k),!Rr&&zl(k)&&(Rr={index:w,id:k.id}),u&&m&&Rr)break}As(Ae,l,Z),_c(Ae,En.artifacts,{suppressTransition:kn}),Kh(),Ol(l),Tr(l),go(!kn),Fh(l),l.length===0&&(ws(),xs=!0,Ha=!1,Mr=null,Ba=!1),!El||Wa?(El=!0,Jo=u?.id??null,Ml=m?.id??null):u&&u.id!==Jo?(Jo=u.id,Hh(u.id)):m&&m.id!==Ml&&Bh(),m&&(Ml=m.id),Nh(l);let v=Ke.lastUserMessageId;u&&u.id!==v&&(Ke.lastUserMessageId=u.id,c.emit("user:message",u)),Ke.lastUserMessageWasVoice=!!u?.viaVoice,Pl(l),Pr()},ql=()=>{Jn!==null&&(cancelAnimationFrame(Jn),Jn=null);let l=er;er=null,l&&ja(l)},Vp=()=>{Jn!==null&&cancelAnimationFrame(Jn),Jn=null,er=null},Jh=l=>{let u=er??qp;if(kn&&u&&Rr&&Gh(u,l,Rr)){er=l,Jn===null&&(Jn=requestAnimationFrame(()=>{Jn=null;let m=er;er=null,m&&ja(m)}));return}if(l.length===0){Vp(),ja(l);return}ql(),ja(l)};F=new Qs(o,{onMessagesChanged(l){Jh(l)},onStatusChanged(l){let u=o.statusIndicator??{};An(B,(v=>v==="idle"?u.idleText??Bt.idle:v==="connecting"?u.connectingText??Bt.connecting:v==="connected"?u.connectedText??Bt.connected:v==="error"?u.errorText??Bt.error:v==="paused"?u.pausedText??Bt.paused:v==="resuming"?u.resumingText??Bt.resuming:Bt[v])(l),u,l)},onStreamingChanged(l){l||(F?.getMessages().length===0?Vp():ql()),kn=l,$a(l),F&&As(Ae,F.getMessages(),Z),l||(go(!0),Ih(),vp=!0,F&&xp(F.getMessages(),Ao(o))),jt(),jd(l?"Responding\u2026":"Response complete."),Pr()},onVoiceStatusChanged(l){if(c.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Yn(),Wr();break;case"processing":Yn(),ay();break;case"speaking":Yn(),iy();break;default:l==="idle"&&F.isBargeInActive()?(Yn(),Wr(),oe?.setAttribute("aria-label","End voice session")):(Ke.active=!1,Yn(),Gn("system"),Ln());break}},onArtifactsState(l){En=l,l.artifacts.length===0&&(wr=!1),_c(Ae,l.artifacts,{suppressTransition:kn}),zn(),Pl()},onReconnect(l){let{executionId:u,lastEventId:m}=l.handle;l.phase==="paused"?c.emit("stream:paused",{executionId:u,after:m}):l.phase==="resuming"?c.emit("stream:resuming",{executionId:u,after:m,attempt:l.attempt??1}):c.emit("stream:resumed",{executionId:u,after:m})}}),at.current=F,Oe.push(()=>F.cancel());let Vl=null;if(F.onReadAloudChange((l,u)=>{ep=l,tp=u,np();let m=l??Vl;l&&(Vl=l);let v=m?F.getMessages().find(w=>w.id===m)??null:null;c.emit("message:read-aloud",{messageId:m,message:v,state:u,timestamp:Date.now()}),u==="idle"&&(Vl=null)}),a=!0,El=!0,o.voiceRecognition?.provider?.type==="runtype")try{F.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&F.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Le||o.onSSEEvent)&&F.setSSEEventCallback((l,u)=>{o.onSSEEvent?.(l,u),_e?.processEvent(l,u),Le?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})});let Kp=()=>{o.resume&&typeof o.reconnectStream=="function"&&F.resumeFromHandle(o.resume)};x?x.then(l=>{if(l){if(l.metadata&&(f=Ed(l.metadata),H.syncFromMetadata()),l.messages?.length){Wa=!0;try{F.hydrateMessages(l.messages)}finally{Wa=!1}}l.artifacts?.length&&F.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>{Op=!0,Kp()}):Kp();let Gp=()=>{!Q()||J||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},Yh=(l,u)=>l?u?{refs:[...l.refs,...u.refs],finalize:async()=>{let[m,v]=await Promise.allSettled([l.finalize(),u.finalize()]),w=[];return m.status==="fulfilled"?w.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),v.status==="fulfilled"?w.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),fS(w)}}:l:u,Xh=()=>{let u=I.getInlineMessageFields?.();return u&&u.contentSegments.some(v=>v.kind==="mention")?u.contentSegments:void 0},Ls=!1,Qh=async l=>{let u=I.value.trim(),m=xt?.hasAttachments()??!1,v=u?await(Jt?.takeInlineCommand(u)??Promise.resolve(null)):null;if(v?.kind==="action"){I.value="",I.style.height="auto",Ps(),Jt?.clear();return}let w=Jt?.collectForSubmit()??null,k=v?.kind==="server"?v.mentions:null,j=Yh(w,k),N=v?.kind==="prompt"?v.sendText:u,q=!!w&&w.refs.length>0;if(!N&&!m&&!q&&!k)return;Gp();let X;m&&(X=[],X.push(...xt.getContentParts()),N&&X.push(lr(N)));let ge=v?.kind==="prompt"?void 0:Xh();I.value="",I.style.height="auto",Ps(),F.sendMessage(N,{contentParts:X,mentions:j??void 0,contentSegments:ge,viaVoice:l?.viaVoice}),m&&xt.clearAttachments(),w&&Jt?.clear()},Kl=async l=>{if(!Ls){Ls=!0;try{await Qh(l)}finally{Ls=!1}}},Ua=l=>{if(l.preventDefault(),F.isStreaming()){F.cancel(),_e?.reset(),we?.update();return}Ls||Kl()},Zh=()=>o.features?.composerHistory!==!1,Gl={...Uc},Jl=!1,Ps=()=>{Gl={...Uc}},ey=()=>F.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),ty=l=>{if(!I)return;Jl=!0,I.value=l,I.dispatchEvent(new Event("input",{bubbles:!0})),Jl=!1;let u=I.value.length;I.setSelectionRange(u,u)},ny=l=>{Jl||(l.isComposing||Jt?.handleInput(l.inputType??void 0),Ps())},oy=l=>{if(I&&!(!l.isComposing&&Jt?.handleKeydown(l))){if(Zh()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=I.selectionStart===0&&I.selectionEnd===0,m=pf({direction:l.key==="ArrowUp"?"up":"down",history:ey(),currentValue:I.value,atStart:u,state:Gl});if(Gl=m.state,m.handled){l.preventDefault(),m.value!==void 0&&ty(m.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(F.isStreaming()){l.preventDefault();return}if(Ls){l.preventDefault();return}Ps(),l.preventDefault(),h.click()}}},Jp=l=>{l.key!=="Escape"||l.isComposing||F.isStreaming()&&l.composedPath().includes(Ce)&&(F.cancel(),_e?.reset(),we?.update(),Ps(),l.preventDefault(),l.stopImmediatePropagation())},ry=async l=>{if(o.attachments?.enabled!==!0||!xt)return;let u=dS(l.clipboardData);u.length!==0&&(l.preventDefault(),await xt.handleFiles(u))},hn=null,Bn=!1,Ir=null,wt=null,Yp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,za=(l="user")=>{if(Bn||F.isStreaming())return;let u=Yp();if(!u)return;hn=new u;let v=(o.voiceRecognition??{}).pauseDuration??2e3;hn.continuous=!0,hn.interimResults=!0,hn.lang="en-US";let w=I.value;hn.onresult=k=>{let j="",N="";for(let X=0;X<k.results.length;X++){let ge=k.results[X],ce=ge[0].transcript;ge.isFinal?j+=ce+" ":N=ce}let q=w+j+N;I.value=q,Ir&&clearTimeout(Ir),(j||N)&&(Ir=window.setTimeout(()=>{I.value.trim()&&hn&&Bn&&(mo(),Kl({viaVoice:!0}))},v))},hn.onerror=k=>{k.error!=="no-speech"&&mo()},hn.onend=()=>{if(Bn){let k=I.value.trim();k&&k!==w.trim()&&Kl({viaVoice:!0}),mo()}};try{if(hn.start(),Bn=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Gn(l),Ln(),oe){let k=o.voiceRecognition??{};wt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??o.sendButton?.size??"40")||24};let j=k.recordingBackgroundColor,N=k.recordingIconColor,q=k.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=j??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let X=oe.querySelector("svg");X&&X.setAttribute("stroke",N)}q&&(oe.style.borderColor=q),oe.setAttribute("aria-label","Stop voice recognition")}}catch{mo("system")}},mo=(l="user")=>{if(Bn){if(Bn=!1,Ir&&(clearTimeout(Ir),Ir=null),hn){try{hn.stop()}catch{}hn=null}if(Ke.active=!1,Gn(l),Ln(),oe){if(oe.classList.remove("persona-voice-recording"),wt){oe.style.backgroundColor=wt.backgroundColor,oe.style.color=wt.color,oe.style.borderColor=wt.borderColor;let u=oe.querySelector("svg");u&&u.setAttribute("stroke",wt.color||"currentColor"),wt=null}oe.setAttribute("aria-label","Start voice recognition")}}},sy=(l,u)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=l?.provider?.type==="runtype",w=l?.provider?.type==="custom";if(!(m||v||w))return null;let j=y("div","persona-send-button-wrapper"),N=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let q=l?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",q);let X=l?.iconName??"mic",ge=u?.size??"40px",ce=l?.iconSize??ge,xe=parseFloat(ce)||24,Ge=l?.backgroundColor??u?.backgroundColor,yt=l?.iconColor??u?.textColor;N.style.width=ce,N.style.height=ce,N.style.minWidth=ce,N.style.minHeight=ce,N.style.fontSize="18px",N.style.lineHeight="1",yt?N.style.color=yt:N.style.color="var(--persona-text, #111827)";let sn=se(X,xe,yt||"currentColor",1.5);sn?N.appendChild(sn):N.textContent="\u{1F3A4}",Ge?N.style.backgroundColor=Ge:N.style.backgroundColor="",l?.borderWidth&&(N.style.borderWidth=l.borderWidth,N.style.borderStyle="solid"),l?.borderColor&&(N.style.borderColor=l.borderColor),l?.paddingX&&(N.style.paddingLeft=l.paddingX,N.style.paddingRight=l.paddingX),l?.paddingY&&(N.style.paddingTop=l.paddingY,N.style.paddingBottom=l.paddingY),j.appendChild(N);let Et=l?.showTooltip??!1;return $t({anchor:N,trigger:j,text:()=>N.getAttribute("aria-label")??q,enabled:Et}),{micButton:N,micButtonWrapper:j}},Yl=()=>{if(!oe||wt)return;let l=o.voiceRecognition??{};wt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Xl=(l,u)=>{if(!oe)return;let m=oe.querySelector("svg");m&&m.remove();let v=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),w=se(l,v,u,1.5);w&&oe.appendChild(w)},qa=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Wr=()=>{if(!oe)return;Yl();let l=o.voiceRecognition??{},u=l.recordingBackgroundColor,m=l.recordingIconColor,v=l.recordingBorderColor;if(qa(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=u??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let w=oe.querySelector("svg");w&&w.setAttribute("stroke",m)}v&&(oe.style.borderColor=v),oe.setAttribute("aria-label","Stop voice recognition")},ay=()=>{if(!oe)return;Yl();let l=o.voiceRecognition??{},u=F.getVoiceInterruptionMode(),m=l.processingIconName??"loader",v=l.processingIconColor??wt?.color??"",w=l.processingBackgroundColor??wt?.backgroundColor??"",k=l.processingBorderColor??wt?.borderColor??"";qa(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=w,oe.style.borderColor=k;let j=v||"currentColor";oe.style.color=j,Xl(m,j),oe.setAttribute("aria-label","Processing voice input"),u==="none"&&(oe.style.cursor="default")},iy=()=>{if(!oe)return;Yl();let l=o.voiceRecognition??{},u=F.getVoiceInterruptionMode(),m=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",v=l.speakingIconName??m,w=l.speakingIconColor??(u==="barge-in"?l.recordingIconColor??wt?.color??"":wt?.color??""),k=l.speakingBackgroundColor??(u==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),j=l.speakingBorderColor??(u==="barge-in"?l.recordingBorderColor??"":wt?.borderColor??"");qa(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=k,oe.style.borderColor=j;let N=w||"currentColor";oe.style.color=N,Xl(v,N);let q=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",q),u==="none"&&(oe.style.cursor="default"),u==="barge-in"&&oe.classList.add("persona-voice-recording")},Yn=()=>{oe&&(qa(),wt&&(oe.style.backgroundColor=wt.backgroundColor??"",oe.style.color=wt.color??"",oe.style.borderColor=wt.borderColor??"",Xl(wt.iconName,wt.color||"currentColor"),wt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Hr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=F.getVoiceStatus(),u=F.getVoiceInterruptionMode();if(u==="none"&&(l==="processing"||l==="speaking"))return;if(u==="cancel"&&(l==="processing"||l==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Ln(),Gn("user"),Yn()});return}F.toggleVoice().then(()=>{Ke.active=F.isVoiceActive(),Ke.manuallyDeactivated=!F.isVoiceActive(),Ln(),Gn("user"),F.isVoiceActive()?Wr():Yn()});return}if(Bn){let l=I.value.trim();Ke.manuallyDeactivated=!0,Ln(),mo("user"),l&&(I.value="",I.style.height="auto",F.sendMessage(l))}else Ke.manuallyDeactivated=!1,Ln(),za("user")};zd=Hr,oe&&(oe.addEventListener("click",Hr),Oe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),Yn()):mo("system"),oe&&oe.removeEventListener("click",Hr)}));let ly=c.on("assistant:complete",()=>{Ap&&(Ke.active||Ke.manuallyDeactivated||Ap==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?F.toggleVoice().then(()=>{Ke.active=F.isVoiceActive(),Gn("auto"),F.isVoiceActive()&&Wr()}):za("auto"))},600))});Oe.push(ly);let cy=c.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});Oe.push(cy);let Xp=()=>{pt(!J,"user")},Lt=null,Yt=null;if(O&&!Q()){let{instance:l,element:u}=sd({config:o,plugins:s,onToggle:Xp});Lt=l,l||(Yt=u)}Lt?e.appendChild(Lt.element):Yt&&e.appendChild(Yt),Ms(),Tr(),jl(),$l(),$a(F.isStreaming()),Pp()||(nn()==="follow"?go(!0):Lp()),Eh(),U&&(!O||Q()?setTimeout(()=>Bl(),0):J&&setTimeout(()=>Bl(),200));let Rs=()=>{if(Q()){Fo(),Ms();return}let l=Mt(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,v=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=m.innerWidth<=w,j=v&&k&&O;try{if(j){_o(),ys=Pa();return}let N=!1;G&&(G=!1,_o(),N=!0);let q=Pa();if(!N&&q!==ys&&(_o(),N=!0),ys=q,N&&Cl(),!O&&!l){ve.style.height="",ve.style.width="";return}if(!u&&!l){let ge=o?.launcher?.width??o?.launcherWidth??xn;ve.style.width=ge,ve.style.maxWidth=ge}La(),lp()}finally{if(Fo(),Ms(),J&&O){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),X=o.launcher?.sidebarMode??!1,ge=o.launcher?.mobileFullscreen??!0,ce=Mt(o)&&ge&&q,xe=X||ge&&q&&O||ce;if(xe&&!Hn){let Ge=e.getRootNode(),yt=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");yt&&!Wn&&(Wn=Kc(yt,o.launcher?.zIndex??_t)),Hn=Gc(e.ownerDocument)}else xe||(Wn?.(),Wn=null,Hn?.(),Hn=null)}}};Rs();let Qp=e.ownerDocument.defaultView??window;if(Qp.addEventListener("resize",Rs),Oe.push(()=>Qp.removeEventListener("resize",Rs)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Fo()});l.observe(Se),Oe.push(()=>l.disconnect())}rn=re.scrollTop;let Zp=_n(re),eu=()=>{let l=re.scrollTop,u=_n(re),m=u<Zp;if(Zp=u,!ao()){rn=l,jt();return}let{action:v,nextLastScrollTop:w}=ki({following:on.isFollowing(),currentScrollTop:l,lastScrollTop:rn,nearBottom:oo(re,Vn),userScrollThreshold:wh,isAutoScrolling:Zt||Ia||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rn=w,v==="resume"){Oa()||uo();return}v==="pause"&&Cs()};if(re.addEventListener("scroll",eu,{passive:!0}),Oe.push(()=>re.removeEventListener("scroll",eu)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Wh(),sc(Ae)});l.observe(Ae),l.observe(re),Oe.push(()=>l.disconnect())}let tu=()=>{ao()&&on.isFollowing()&&Oa()&&Cs()},nu=re.ownerDocument;nu.addEventListener("selectionchange",tu),Oe.push(()=>{nu.removeEventListener("selectionchange",tu)});let dy=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),ou=l=>{dy.has(l.key)&&(Yo(),Fd()&&ao()&&on.isFollowing()&&Cs())},ru=l=>{l.target?.closest("a, button, [tabindex], input, textarea, select")&&(Yo(),Fd()&&ao()&&on.isFollowing()&&Cs())};re.addEventListener("keydown",ou),re.addEventListener("focusin",ru),Oe.push(()=>{re.removeEventListener("keydown",ou),re.removeEventListener("focusin",ru)});let su=l=>{if(l.deltaY!==0&&Yo(),!ao())return;let u=Li({following:on.isFollowing(),deltaY:l.deltaY,nearBottom:oo(re,Vn),resumeWhenNearBottom:!0});u==="pause"?Cs():u==="resume"&&!Oa()&&uo()};re.addEventListener("wheel",su,{passive:!0}),re.addEventListener("touchmove",Yo,{passive:!0}),re.addEventListener("pointerdown",Yo,{passive:!0}),Oe.push(()=>{re.removeEventListener("touchmove",Yo),re.removeEventListener("pointerdown",Yo)}),Oe.push(()=>re.removeEventListener("wheel",su)),Rt.addEventListener("click",()=>{ws(),re.scrollTop=re.scrollHeight,rn=re.scrollTop,uo(),go(!0),jt()}),Oe.push(()=>Rt.remove()),Oe.push(()=>{Ep(),ws()});let au=()=>{pe&&(zo&&(pe.removeEventListener("click",zo),zo=null),le()?(pe.style.display="",zo=()=>{pt(!1,"user")},pe.addEventListener("click",zo)):pe.style.display="none")};au(),(()=>{let{clearChatButton:l}=Te;l&&l.addEventListener("click",()=>{F.clearMessages(),Vo.clear(),uo(),ar(Te.composerOverlay);try{localStorage.removeItem(cs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==cs)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 u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(u),b?.clear&&Ll(()=>b.clear(),"[AgentWidget] Failed to clear storage adapter:"),f={},H.syncFromMetadata(),Le?.clear(),_e?.reset(),we?.update()})})(),R&&R.addEventListener("submit",Ua);let iu=[["keydown",oy],["input",ny],["paste",ry],["focus",mh]],Ql=l=>{if(l)for(let[u,m]of iu)l.addEventListener(u,m)},Zl=l=>{if(l)for(let[u,m]of iu)l.removeEventListener(u,m)};Ql(I);let lu=()=>{Jt?.onComposerSwap((l,u)=>{Zl(u),I=l,Ql(l)})};lu();let ec=!1;function py(){if(!ec){ec=!0;try{let l=I?.value??"",u=Se.ownerDocument??document,m=I?u.activeElement===I:!1;Zl(I),R?.removeEventListener("submit",Ua),oe?.removeEventListener("click",Hr),Jt?.destroy(),Jt=null;let v=null,w=()=>(v=Q()?ji({config:o}):es({config:o}),v.footer),k=Kd(w)??w();Ze.replaceComposer(k),Se=Ze.composer.footer;let j=v!==null&&k===v.footer;yl=!j,wa=j?v.setSendButtonMode:()=>{},Vd(Se),Jd(Se),Yd(),Xd(),Qd(),lu(),R&&R.addEventListener("submit",Ua),Ql(I),oe?.addEventListener("click",Hr);let N=Uo.indexOf(qn);qn.destroy(),qn=ua(E),N>=0&&(Uo[N]=qn),I&&(I.value=l),jl(),Tr(),$a(F.isStreaming()),_o(),Fo(),m&&I?.focus()}finally{ec=!1}}}let cu=e.ownerDocument??document;cu.addEventListener("keydown",Jp,!0);let du="persona-attachment-drop-active",Is=0,tc=()=>{Is=0,Ce.classList.remove(du)},Br=()=>o.attachments?.enabled===!0&&xt!==null,pu=l=>{!ol(l.dataTransfer)||!Br()||(Is++,Is===1&&Ce.classList.add(du))},uu=l=>{!ol(l.dataTransfer)||!Br()||(Is--,Is<=0&&tc())},gu=l=>{!ol(l.dataTransfer)||!Br()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},fu=l=>{if(!ol(l.dataTransfer)||!Br())return;l.preventDefault(),l.stopPropagation(),tc();let u=Array.from(l.dataTransfer.files??[]);u.length!==0&&xt.handleFiles(u)},ho=!0;Ce.addEventListener("dragenter",pu,ho),Ce.addEventListener("dragleave",uu,ho),e.addEventListener("dragover",gu,ho),e.addEventListener("drop",fu,ho);let Va=e.ownerDocument,mu=l=>{Br()&&l.preventDefault()},hu=l=>{Br()&&l.preventDefault()};Va.addEventListener("dragover",mu),Va.addEventListener("drop",hu),Oe.push(()=>{R&&R.removeEventListener("submit",Ua),Zl(I),cu.removeEventListener("keydown",Jp,!0),Jt?.destroy()}),Oe.push(()=>{Ce.removeEventListener("dragenter",pu,ho),Ce.removeEventListener("dragleave",uu,ho),e.removeEventListener("dragover",gu,ho),e.removeEventListener("drop",fu,ho),Va.removeEventListener("dragover",mu),Va.removeEventListener("drop",hu),tc()}),Oe.push(()=>{F.cancel()}),Lt?Oe.push(()=>{Lt?.destroy()}):Yt&&Oe.push(()=>{Yt?.remove()});let It={update(l){let u=o.toolCall,m=o.messageActions,v=o.layout?.messages,w=o.colorScheme,k=o.loadingIndicator,j=o.iterationDisplay,N=o.features?.showReasoning,q=o.features?.showToolCalls,X=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,ce=o.features?.streamAnimation?.type;o=Zi({...o,features:r},l),r=o.features,o=Xi(o),Al(),Gr(e,o),va(e,o),xa(e,o),zn(),o.colorScheme!==w&&cp();let xe=Qi.getForInstance(o.plugins);s.length=0,s.push(...xe),O=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,ue=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,be=o.features?.scrollToBottom??{};let Ge=nn();he=o.features?.scrollBehavior??{},Ge!==nn()&&(ws(),uo()),wp(),Ud(),jt();let yt=fe;if(fe=o.features?.showEventStreamToggle??!1,fe&&!yt){if(Le||($e=new ya(rt),Le=new ha(Ve,$e),_e=_e??new ba,$e.open().then(()=>Le?.restore()).catch(()=>{}),F.setSSEEventCallback((ie,qe)=>{o.onSSEEvent?.(ie,qe),_e?.processEvent(ie,qe),Le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ie,timestamp:Date.now(),payload:JSON.stringify(qe)})})),!Xe&&He){let ie=o.features?.eventStream?.classNames,qe="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"+(ie?.toggleButton?" "+ie.toggleButton:"");Xe=y("button",qe),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=Gt.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let ht=se("activity","18px","currentColor",1.5);ht&&Xe.appendChild(ht);let Qe=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Vt=Qe||ot;Vt&&Vt.parentNode===He?He.insertBefore(Xe,Vt):He.appendChild(Xe),Xe.addEventListener("click",()=>{ae?fs():ml()})}}else!fe&&yt&&(fs(),Xe&&(Xe.remove(),Xe=null),Le?.clear(),$e?.destroy(),Le=null,$e=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Lt&&(Lt.destroy(),Lt=null),o.launcher?.enabled===!1&&Yt&&(Yt.remove(),Yt=null),o.launcher?.enabled!==!1&&!Lt&&!Yt){let{instance:ie,element:qe}=sd({config:o,plugins:s,onToggle:Xp});Lt=ie,ie||(Yt=qe),e.appendChild(qe)}Lt&&Lt.update(o),ze&&o.launcher?.title!==void 0&&(ze.textContent=o.launcher.title),je&&o.launcher?.subtitle!==void 0&&(je.textContent=o.launcher.subtitle);let ut=o.layout?.header;if(ut?.layout!==A&&He){let ie=ut?ga(o,ut,{showClose:le(),onClose:()=>pt(!1,"user")}):Ho({config:o,showClose:le(),onClose:()=>pt(!1,"user")});Ze.replaceHeader(ie),He=Ze.header.element,Pe=Ze.header.iconHolder,ze=Ze.header.headerTitle,je=Ze.header.headerSubtitle,pe=Ze.header.closeButton,A=ut?.layout}else if(ut){if(Pe&&(Pe.style.display=ut.showIcon===!1?"none":""),ze&&(ze.style.display=ut.showTitle===!1?"none":""),je&&(je.style.display=ut.showSubtitle===!1?"none":""),pe){let ie=le()&&ut.showCloseButton!==!1;pe.style.display=ie?"":"none"}if(Te.clearChatButtonWrapper){let ie=ut.showClearChat;if(ie!==void 0){Te.clearChatButtonWrapper.style.display=ie?"":"none";let{closeButtonWrapper:qe}=Te;qe&&!qe.classList.contains("persona-absolute")&&(ie?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;He&&(He.style.display=Et?"":"none");let Wt=o.layout?.showFooter!==!1;Se&&(Se.style.display=Wt?"":"none"),Fo(),jt(),O!==Y?O?pt(_,"auto"):(J=!0,Ms()):_!==z&&pt(_,"auto"),z=_,Y=O,Rs(),au();let Ne=JSON.stringify(o.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(o.messageActions)!==JSON.stringify(m),Tt=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),gt=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,Nt=o.iterationDisplay!==j,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(X)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);(Ne||Ee||Tt||gt||Nt||ft)&&F&&(Tl++,As(Ae,F.getMessages(),Z));let Ht=o.features?.streamAnimation?.type;if(Ht!==ce&&Ht&&Ht!=="none"){let ie=Qr(Ht,o.features?.streamAnimation?.plugins);ie&&Wi(ie,e)}let We=o.launcher??{},Fe=We.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,zt=Fe||Ut===!1,At=We.headerIconName,it=We.headerIconSize??"48px";if(Pe){let ie=Ce.querySelector(".persona-border-b-persona-divider"),qe=ie?.querySelector(".persona-flex-col");if(zt)Pe.style.display="none",ie&&qe&&!ie.contains(qe)&&ie.insertBefore(qe,ie.firstChild);else{if(Pe.style.display="",Pe.style.height=it,Pe.style.width=it,ie&&qe&&(ie.contains(Pe)?Pe.nextSibling!==qe&&(Pe.remove(),ie.insertBefore(Pe,qe)):ie.insertBefore(Pe,qe)),At){let Qe=parseFloat(it)||24,ot=se(At,Qe*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let Qe=Pe.querySelector("img");if(Qe)Qe.src=We.iconUrl,Qe.style.height=it,Qe.style.width=it;else{let ot=document.createElement("img");ot.src=We.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=it,ot.style.width=it,Pe.replaceChildren(ot)}}else{let Qe=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Qe||ot)&&Pe.replaceChildren(),Pe.textContent=We.agentIconText??"\u{1F4AC}"}let ht=Pe.querySelector("img");ht&&(ht.style.height=it,ht.style.width=it)}}let mt=o.layout?.header?.showTitle,Ye=o.layout?.header?.showSubtitle;if(ze&&(ze.style.display=mt===!1?"none":""),je&&(je.style.display=Ye===!1?"none":""),pe){let ie=le()&&o.layout?.header?.showCloseButton!==!1;pe.style.display=ie?"":"none";let qe=We.closeButtonSize??"32px",ht=We.closeButtonPlacement??"inline";pe.style.height=qe,pe.style.width=qe;let{closeButtonWrapper:Qe}=Te,ot=ht==="top-right",Vt=Qe?.classList.contains("persona-absolute");if(Qe&&ot!==Vt)if(Qe.remove(),ot)Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(Qe);else{let bo=We.clearChat?.placement??"inline",Bs=We.clearChat?.enabled??!0;Qe.className=Bs&&bo==="inline"?"":"persona-ml-auto";let yu=Ce.querySelector(".persona-border-b-persona-divider");yu&&yu.appendChild(Qe)}if(pe.style.color=We.closeButtonColor||Gt.actionIconColor,We.closeButtonBackgroundColor?(pe.style.backgroundColor=We.closeButtonBackgroundColor,pe.classList.remove("hover:persona-bg-gray-100")):(pe.style.backgroundColor="",pe.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let bo=We.closeButtonBorderWidth||"0px",Bs=We.closeButtonBorderColor||"transparent";pe.style.border=`${bo} solid ${Bs}`,pe.classList.remove("persona-border-none")}else pe.style.border="",pe.classList.add("persona-border-none");We.closeButtonBorderRadius?(pe.style.borderRadius=We.closeButtonBorderRadius,pe.classList.remove("persona-rounded-full")):(pe.style.borderRadius="",pe.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(pe.style.paddingLeft=We.closeButtonPaddingX,pe.style.paddingRight=We.closeButtonPaddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),We.closeButtonPaddingY?(pe.style.paddingTop=We.closeButtonPaddingY,pe.style.paddingBottom=We.closeButtonPaddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let an=We.closeButtonIconName??"x",Pn=We.closeButtonIconText??"\xD7";pe.innerHTML="";let Ft=se(an,"28px","currentColor",1);Ft?(Ft.style.display="block",pe.appendChild(Ft)):pe.textContent=Pn;let Kt=We.closeButtonTooltipText??"Close chat",Qn=We.closeButtonShowTooltip??!0;pe.setAttribute("aria-label",Kt),Qe&&$t({anchor:pe,trigger:Qe,text:()=>pe?.getAttribute("aria-label")??Kt,enabled:Qn})}let{clearChatButton:De,clearChatButtonWrapper:bt}=Te;if(De){let ie=We.clearChat??{},qe=ie.enabled??!0,ht=o.layout?.header?.showClearChat,Qe=ht!==void 0?ht:qe,ot=ie.placement??"inline";if(bt){bt.style.display=Qe?"":"none";let{closeButtonWrapper:Vt}=Te;!Q()&&Vt&&!Vt.classList.contains("persona-absolute")&&(Qe?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let an=ot==="top-right",Pn=bt.classList.contains("persona-absolute");if(!Q()&&an!==Pn&&Qe){if(bt.remove(),an)bt.className="persona-absolute persona-top-4 persona-z-50",bt.style.right="48px",Ce.style.position="relative",Ce.appendChild(bt);else{bt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bt.style.right="";let Kt=Ce.querySelector(".persona-border-b-persona-divider"),Qn=Te.closeButtonWrapper;Kt&&Qn&&Qn.parentElement===Kt?Kt.insertBefore(bt,Qn):Kt&&Kt.appendChild(bt)}let Ft=Te.closeButtonWrapper;Ft&&!Ft.classList.contains("persona-absolute")&&(an?Ft.classList.add("persona-ml-auto"):Ft.classList.remove("persona-ml-auto"))}}if(Qe){if(!Q()){let bo=ie.size??"32px";De.style.height=bo,De.style.width=bo}let Vt=ie.iconName??"refresh-cw",an=ie.iconColor??"";De.style.color=an||Gt.actionIconColor,De.innerHTML="";let Pn=Q()?"14px":"20px",Ft=se(Vt,Pn,"currentColor",1);if(Ft&&(Ft.style.display="block",De.appendChild(Ft)),ie.backgroundColor?(De.style.backgroundColor=ie.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),ie.borderWidth||ie.borderColor){let bo=ie.borderWidth||"0px",Bs=ie.borderColor||"transparent";De.style.border=`${bo} solid ${Bs}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");ie.borderRadius?(De.style.borderRadius=ie.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),ie.paddingX?(De.style.paddingLeft=ie.paddingX,De.style.paddingRight=ie.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),ie.paddingY?(De.style.paddingTop=ie.paddingY,De.style.paddingBottom=ie.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Kt=ie.tooltipText??"Clear chat",Qn=ie.showTooltip??!0;De.setAttribute("aria-label",Kt),bt&&$t({anchor:De,trigger:bt,text:()=>De?.getAttribute("aria-label")??Kt,enabled:Qn})}}let qt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[el],bn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ls.message,ls.messageAndClick];H=tl({parsers:qt,handlers:bn,getSessionMetadata:M,updateSessionMetadata:P,emit:c.emit,documentRef:typeof document<"u"?document:null}),Z=km(o,H,ye),F.updateConfig(o),As(Ae,F.getMessages(),Z),Tr(),jl(),Vh(),$a(F.isStreaming());let Ws=o.voiceRecognition?.enabled===!0,Ka=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Pt=o.voiceRecognition?.provider?.type==="runtype";if(Ws&&(Ka||Pt))if(!oe||!gn){let ie=sy(o.voiceRecognition,o.sendButton);ie&&(oe=ie.micButton,gn=ie.micButtonWrapper,St.insertBefore(gn,W),oe.addEventListener("click",Hr),oe.disabled=F.isStreaming())}else{let ie=o.voiceRecognition??{},qe=o.sendButton??{},ht=ie.iconName??"mic",Qe=qe.size??"40px",ot=ie.iconSize??Qe,Vt=parseFloat(ot)||24;oe.style.width=ot,oe.style.height=ot,oe.style.minWidth=ot,oe.style.minHeight=ot;let an=ie.iconColor??qe.textColor;oe.innerHTML="";let Pn=se(ht,Vt,an||"currentColor",1.5);Pn?oe.appendChild(Pn):oe.textContent="\u{1F3A4}";let Ft=ie.backgroundColor??qe.backgroundColor;Ft?oe.style.backgroundColor=Ft:oe.style.backgroundColor="",an?oe.style.color=an:oe.style.color="var(--persona-text, #111827)",ie.borderWidth?(oe.style.borderWidth=ie.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),ie.borderColor?oe.style.borderColor=ie.borderColor:oe.style.borderColor="",ie.paddingX?(oe.style.paddingLeft=ie.paddingX,oe.style.paddingRight=ie.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),ie.paddingY?(oe.style.paddingTop=ie.paddingY,oe.style.paddingBottom=ie.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Kt=ie.tooltipText??"Start voice recognition",Qn=ie.showTooltip??!1;oe.setAttribute("aria-label",Kt),gn&&$t({anchor:oe,trigger:gn,text:()=>oe?.getAttribute("aria-label")??Kt,enabled:Qn}),gn.style.display="",oe.disabled=F.isStreaming()}else oe&&gn&&(gn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?F.isVoiceActive()&&F.toggleVoice():Bn&&mo());if(o.attachments?.enabled===!0){if(!fn||!dt){let ie=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Tn||(Tn=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Tn.style.display="none",R.insertBefore(Tn,I)),kt||(kt=document.createElement("input"),kt.type="file",kt.accept=(ie.allowedTypes??no).join(","),kt.multiple=(ie.maxFiles??4)>1,kt.style.display="none",kt.setAttribute("aria-label","Attach files"),R.insertBefore(kt,I)),fn=y("div","persona-send-button-wrapper"),dt=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),dt.type="button",dt.setAttribute("aria-label",ie.buttonTooltipText??"Attach file");let Qe=ie.buttonIconName??"paperclip",ot=ht,Vt=parseFloat(ot)||40,an=Math.round(Vt*.6);dt.style.width=ot,dt.style.height=ot,dt.style.minWidth=ot,dt.style.minHeight=ot,dt.style.fontSize="18px",dt.style.lineHeight="1";let Pn=se(Qe,an,"currentColor",1.5);Pn?dt.appendChild(Pn):dt.textContent="\u{1F4CE}",dt.addEventListener("click",Kt=>{Kt.preventDefault(),kt?.click()}),fn.appendChild(dt);let Ft=ie.buttonTooltipText??"Attach file";$t({anchor:dt,trigger:fn,text:()=>dt?.getAttribute("aria-label")??Ft}),un?un.append(fn):R.appendChild(fn),!xt&&kt&&Tn&&(xt=Kr.fromConfig(ie),xt.setPreviewsContainer(Tn),kt.addEventListener("change",async()=>{xt&&kt?.files&&(await xt.handleFileSelect(kt.files),kt.value="")}))}else{fn.style.display="";let ie=o.attachments??{};kt&&(kt.accept=(ie.allowedTypes??no).join(","),kt.multiple=(ie.maxFiles??4)>1),xt&&xt.updateConfig({allowedTypes:ie.allowedTypes,maxFileSize:ie.maxFileSize,maxFiles:ie.maxFiles})}if(Ce.querySelector(".persona-attachment-drop-overlay")?.remove(),Ce.appendChild(Lm(o.attachments?.dropOverlay)),dt){let ie=o.attachments??{},qe=ie.buttonTooltipText??"Attach file";dt.setAttribute("aria-label",qe),dt.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,Qe=se(ie.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);Qe?dt.appendChild(Qe):dt.textContent="\u{1F4CE}",fn&&$t({anchor:dt,trigger:fn,text:()=>dt?.getAttribute("aria-label")??qe})}}else fn&&(fn.style.display="none"),xt&&xt.clearAttachments(),Ce.querySelector(".persona-attachment-drop-overlay")?.remove();let Ot=o.sendButton??{},Hs=Ot.useIcon??!1,Ja=Ot.iconText??"\u2191",Dr=Ot.iconName,Ya=Ot.tooltipText??"Send message",nc=Ot.showTooltip??!1,tr=Ot.size??"40px",Xn=Ot.backgroundColor,nr=Ot.textColor;if(Hs){if(h.style.width=tr,h.style.height=tr,h.style.minWidth=tr,h.style.minHeight=tr,h.style.fontSize="18px",h.style.lineHeight="1",nr?h.style.color=nr:h.style.color="var(--persona-button-primary-fg, #ffffff)",!F.isStreaming())if(h.innerHTML="",Dr){let ie=parseFloat(tr)||24,qe=nr?.trim()||"currentColor",ht=se(Dr,ie,qe,2);ht?h.appendChild(ht):h.textContent=Ja}else h.textContent=Ja;h.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Xn?(h.style.backgroundColor=Xn,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary"))}else h.textContent=o.copy?.sendButtonLabel??"Send",h.style.width="",h.style.height="",h.style.minWidth="",h.style.minHeight="",h.style.fontSize="",h.style.lineHeight="",h.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",Xn?(h.style.backgroundColor=Xn,h.classList.remove("persona-bg-persona-accent")):h.classList.add("persona-bg-persona-accent"),nr?h.style.color=nr:h.classList.add("persona-text-white");Ot.borderWidth?(h.style.borderWidth=Ot.borderWidth,h.style.borderStyle="solid"):(h.style.borderWidth="",h.style.borderStyle=""),Ot.borderColor?h.style.borderColor=Ot.borderColor:h.style.borderColor="",Ot.paddingX?(h.style.paddingLeft=Ot.paddingX,h.style.paddingRight=Ot.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),Ot.paddingY?(h.style.paddingTop=Ot.paddingY,h.style.paddingBottom=Ot.paddingY):(h.style.paddingTop="",h.style.paddingBottom=""),F.isStreaming()||h.setAttribute("aria-label",Ya),W&&$t({anchor:h,trigger:W,text:()=>h.getAttribute("aria-label")??Ya,enabled:nc});let Or=Eo(o,Q());Sl(),Or?(Ae.style.maxWidth=Or,Ae.style.marginLeft="auto",Ae.style.marginRight="auto",Ae.style.width="100%",K.style.maxWidth=Or,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",R&&(R.style.maxWidth=Or,R.style.marginLeft="auto",R.style.marginRight="auto"),E&&(E.style.maxWidth=Or,E.style.marginLeft="auto",E.style.marginRight="auto"),B.style.maxWidth=Or,B.style.marginLeft="auto",B.style.marginRight="auto"):(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight="",Ae.style.width="",K.style.maxWidth="",K.style.marginLeft="",K.style.marginRight="",K.style.width="",R&&(R.style.maxWidth="",R.style.marginLeft="",R.style.marginRight=""),E&&(E.style.maxWidth="",E.style.marginLeft="",E.style.marginRight=""),B.style.maxWidth="",B.style.marginLeft="",B.style.marginRight="");let yo=o.statusIndicator??{},uy=yo.visible??!0;if(B.style.display=uy?"":"none",F){let ie=F.getStatus();An(B,(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])(ie),yo,ie)}B.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gy=yo.align==="left"?"persona-text-left":yo.align==="center"?"persona-text-center":"persona-text-right";B.classList.add(gy)},open(){le()&&pt(!0,"api")},close(){le()&&pt(!1,"api")},toggle(){le()&&pt(!J,"api")},reconnect(){F.reconnectNow()},clearChat(){Un=!1,F.clearMessages(),Vo.clear(),uo();try{localStorage.removeItem(cs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cs}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==cs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),b?.clear&&Ll(()=>b.clear(),"[AgentWidget] Failed to clear storage adapter:"),f={},H.syncFromMetadata(),Le?.clear(),_e?.reset(),we?.update()},setMessage(l){return!I||F.isStreaming()?!1:(!J&&le()&&pt(!0,"system"),I.value=l,I.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=l?.trim()||I.value.trim();return u?(!J&&le()&&pt(!0,"system"),I.value="",I.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){return F.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(F.isVoiceActive()||(!J&&le()&&pt(!0,"system"),Ke.manuallyDeactivated=!1,Ln(),F.toggleVoice().then(()=>{Ke.active=F.isVoiceActive(),Gn("user"),F.isVoiceActive()&&Wr()})),!0):Bn?!0:Yp()?(!J&&le()&&pt(!0,"system"),Ke.manuallyDeactivated=!1,Ln(),za("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Ln(),Gn("user"),Yn()}),!0):!1:Bn?(Ke.manuallyDeactivated=!0,Ln(),mo("user"),!0):!1},injectMessage(l){return!J&&le()&&pt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!J&&le()&&pt(!0,"system");let u=F.injectAssistantMessage(l);return me&&(me=!1,ee&&(clearTimeout(ee),ee=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!J&&le()&&pt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!J&&le()&&pt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!J&&le()&&pt(!0,"system"),F.injectMessageBatch(l)},injectComponentDirective(l){return!J&&le()&&pt(!0,"system"),F.injectComponentDirective(l)},injectTestMessage(l){!J&&le()&&pt(!0,"system"),F.injectTestEvent(l)},async connectStream(l,u){return F.connectStream(l,u)},__pushEventStreamEvent(l){Le&&(_e?.processEvent(l.type,l.payload),Le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!fe||!Le||ml()},hideEventStream(){ae&&fs()},isEventStreamVisible(){return ae},showArtifacts(){Qt(o)&&(Un=!1,wr=!0,zn(),Je?.setMobileOpen(!0))},hideArtifacts(){Qt(o)&&(Un=!0,zn())},upsertArtifact(l){return Qt(o)?(to(o.features?.artifacts,{artifactType:l.artifactType,...l.artifactType==="markdown"&&l.file?{file:l.file}:{},...l.presentation?{presentation:l.presentation}:{}})==="panel"&&(Un=!1,wr=!0),F.upsertArtifact(l)):null},selectArtifact(l){Qt(o)&&F.selectArtifact(l)},clearArtifacts(){Qt(o)&&F.clearArtifacts()},getArtifacts(){return F?.getArtifacts()??[]},getSelectedArtifactId(){return F?.getSelectedArtifactId()??null},focusInput(){return O&&!J&&!Q()||!I?!1:(I.focus(),!0)},async resolveApproval(l,u,m){let w=F.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===l);if(!w?.approval)throw new Error(`Approval not found: ${l}`);if(w.approval.toolType==="webmcp"){F.resolveWebMcpApproval(w.id,u);return}return F.resolveApproval(w.approval,u,m)},setFollowUpSuggestions(l){xh(l)},clearFollowUpSuggestions(){Cp()},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...f}},updatePersistentMetadata(l){P(l)},on(l,u){return c.on(l,u)},off(l,u){c.off(l,u)},isOpen(){return le()&&J},isVoiceActive(){return Ke.active},toggleReadAloud(l){F.toggleReadAloud(l)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(l){return F.getReadAloudState(l)},onReadAloudChange(l){return F.onReadAloudChange(l)},getState(){return{open:le()&&J,launcherEnabled:O,voiceActive:Ke.active,streaming:F.isStreaming()}},showCSATFeedback(l){!J&&le()&&pt(!0,"system");let u=Ae.querySelector(".persona-feedback-container");u&&u.remove();let m=Sd({onSubmit:async(v,w)=>{F.isClientTokenMode()&&await F.submitCSATFeedback(v,w),l?.onSubmit?.(v,w)},onDismiss:l?.onDismiss,...l});Ae.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!J&&le()&&pt(!0,"system");let u=Ae.querySelector(".persona-feedback-container");u&&u.remove();let m=Td({onSubmit:async(v,w)=>{F.isClientTokenMode()&&await F.submitNPSFeedback(v,w),l?.onSubmit?.(v,w)},onDismiss:l?.onDismiss,...l});Ae.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){ql(),Zo!=null&&(clearInterval(Zo),Zo=null),Oe.forEach(l=>l()),ke.remove(),tt?.remove(),Lt?.destroy(),Yt?.remove(),zo&&pe.removeEventListener("click",zo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,u={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=u,Oe.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=N=>{let q=N.detail;(!q?.instanceId||q.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",u),Oe.push(()=>{window.removeEventListener("persona:focusInput",u)}),fe){let N=X=>{let ge=X.detail;(!ge?.instanceId||ge.instanceId===l)&&It.showEventStream()},q=X=>{let ge=X.detail;(!ge?.instanceId||ge.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",q),Oe.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",q)})}let m=N=>{let q=N.detail;(!q?.instanceId||q.instanceId===l)&&It.showArtifacts()},v=N=>{let q=N.detail;(!q?.instanceId||q.instanceId===l)&&It.hideArtifacts()},w=N=>{let q=N.detail;q?.instanceId&&q.instanceId!==l||q?.artifact&&It.upsertArtifact(q.artifact)},k=N=>{let q=N.detail;q?.instanceId&&q.instanceId!==l||typeof q?.id=="string"&&It.selectArtifact(q.id)},j=N=>{let q=N.detail;(!q?.instanceId||q.instanceId===l)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",w),window.addEventListener("persona:selectArtifact",k),window.addEventListener("persona:clearArtifacts",j),Oe.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",w),window.removeEventListener("persona:selectArtifact",k),window.removeEventListener("persona:clearArtifacts",j)})}let yn=pS(o.persistState);if(yn&&le()){let l=uS(yn.storage),u=`${yn.keyPrefix}widget-open`,m=`${yn.keyPrefix}widget-voice`,v=`${yn.keyPrefix}widget-voice-mode`;if(l){let w=yn.persist?.openState&&l.getItem(u)==="true",k=yn.persist?.voiceState&&l.getItem(m)==="true",j=yn.persist?.voiceState&&l.getItem(v)==="true";if(w&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{It.open(),setTimeout(()=>{if(k||j)It.startVoiceRecognition();else if(yn.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0)),yn.persist?.openState&&(c.on("widget:opened",()=>{l.setItem(u,"true")}),c.on("widget:closed",()=>{l.setItem(u,"false")})),yn.persist?.voiceState&&(c.on("voice:state",N=>{l.setItem(m,N.active?"true":"false")}),c.on("user:message",N=>{l.setItem(v,N.viaVoice?"true":"false")})),yn.clearOnChatClear){let N=()=>{l.removeItem(u),l.removeItem(m),l.removeItem(v)},q=()=>N();window.addEventListener("persona:clear-chat",q),Oe.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(C&&le()&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{It.open()},0)),Pr(),!Ch){let l=Ds(()=>{F&&(Tl++,Vo.clear(),As(Ae,F.getMessages(),Z))});Oe.push(l)}return It};var Pm=(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},mS=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},hS=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},yS=(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.")},Rm=(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"},Rd=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=""},Im=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Rd(e)},kd=e=>{e.style.transition=""},Ld=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=""},Pd=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},rl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},bS=(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))},vS=(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)},xS=e=>{let t=ur(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Xt(t,r)??r;return{inset:o(n?.inset,hi),canvasBackground:o(n?.canvasBackground,yi)}},Wm=(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},CS=(e,t,n,o,r,s,a,i)=>{let p=cn(s),d=p.reveal==="push",c=i!=null,g=i?.inset??"",b=i?.canvasBackground??"";bS(e,t,n,o,d),vS(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,x=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,S=f!=null?f.innerWidth<=C:!1;if(x&&S&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ld(t),kd(o),Im(o),Pd(n),rl(r,o),Wm(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??_t),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Im(o),mS(o,p.maxHeight),Wm(o,c&&a,g,b),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ld(t),kd(o),Pd(n),rl(r,o);let P=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",L=a?"translateX(0)":T;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=P,o.style.transform=L,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",kd(o),Rd(o),rl(r,o);let P=Pm(p.width,e.clientWidth),T=Math.max(0,e.clientWidth),L=p.animate?"margin-left 180ms ease":"none",H=p.side==="right"?a?-P:0:a?0:-P;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=`${T+P}px`,t.style.transition=L,t.style.marginLeft=`${H}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${T}px`,n.style.maxWidth=`${T}px`,n.style.minWidth=`${T}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ld(t),Rd(o),Pd(n),rl(r,o);let P=p.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let T=a?p.width:"0px",L=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",H=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${T}`,o.style.width=T,o.style.maxWidth=T,o.style.minWidth=T,o.style.minHeight="0",hS(o,p.maxHeight),o.style.overflow=P||H?"hidden":"visible",o.style.transition=L,P){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let O=c?`calc(${Pm(p.width,e.clientWidth)}px - (2 * ${g}))`:p.width;r.style.width=O,r.style.minWidth=O,r.style.maxWidth=O,r.style.boxSizing="border-box"}}},wS=(e,t)=>{let n=e.ownerDocument.createElement("div");return Rm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Rm(n,o)},destroy(){n.remove()}}},AS=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let b=null,f=()=>{b?.disconnect(),b=null},x=null,C=()=>{x=t?.launcher?.detachedPanel===!0?xS(t):null};C();let S=()=>{CS(a,i,p,d,c,t,g,x)},M=null,P=()=>{M?.(),M=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(M=na(()=>{C(),S()}))},T=()=>{f(),cn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{S()}),b.observe(a)))},L=!1,H=()=>{S(),T(),g&&!L&&a.dataset.personaDockMobileFullscreen!=="true"&&(L=!0,yS(a,cn(t)))},O=a.ownerDocument.defaultView,_=()=>{H()};return O?.addEventListener("resize",_),cn(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),H(),P(),{mode:"docked",host:c,shell:a,syncWidgetState(U){let z=U.launcherEnabled?U.open:!0;g!==z&&(g=z,H())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(g=!0),C(),H(),P()},destroy(){O?.removeEventListener("resize",_),M?.(),M=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},sl=(e,t)=>Mt(t)?AS(e,t):wS(e,t);var SS=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},Hm=(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)},Bm=e=>{let t=SS(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=sl(t,r),a,i=[],p=(S,M)=>{let T=!(M?.launcher?.enabled??!0)||Mt(M),L=o.createElement("div");if(L.setAttribute("data-persona-root","true"),T&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0",L.style.minWidth="0"),n){let H=S.attachShadow({mode:"open"});H.appendChild(L),Hm(H,o)}else S.appendChild(L),Hm(S,o);return t.id&&L.setAttribute("data-persona-instance",t.id),L},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},g=()=>{let S=p(s.host,r);a=Md(S,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(S=>S()),i=[],a.destroy()};g(),e.onChatReady?.();let f=S=>{b(),s.destroy(),s=sl(t,S),r=S,g()},x={update(S){let M=Zi(r??{},S),P=Mt(r),T=Mt(M),L=Wo(r),H=Wo(M);if(P!==T||L!==H){f(M);return}r=M,s.updateConfig(r),a.update(S),d()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(x,{get(S,M,P){if(M==="host")return s.host;if(M in S)return Reflect.get(S,M,P);let T=a[M];return typeof T=="function"?T.bind(a):T}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function TS(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 ES(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:TS(o,n)?2:3}function Dm(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Id(e,t){let n=t.trim();if(!n)return[...e].sort(Dm);let o=[];for(let r of e){let s=ES(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Dm(r.item,s.item)),o.map(r=>r.item)}function MS(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 kS(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Id(e.items,t),resolve:e.resolve}}function LS(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=>Id(t,MS(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 $m=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),PS=new Set(["button","a","input","select","textarea","details","summary"]),RS=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Wd=/\b(product|card|item|listing|result)\b/i,Bd=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,IS=3e3,WS=100;function jm(e){let t=typeof e.className=="string"?e.className:"";if(Wd.test(t)||e.id&&Wd.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Wd.test(o.value))return!0}return!1}function Um(e){return Bd.test((e.textContent??"").trim())}function zm(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 HS(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Om(e){let t=e.match(Bd);return t?t[0]:null}function Nm(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 BS(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 DS="commerce-card",OS="result-card";function Fm(e){return!jm(e)||!Um(e)||!zm(e)&&!HS(e)?0:5200}function _m(e){return!jm(e)||Um(e)||!zm(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var qm=[{id:DS,scoreElement(e){return Fm(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||Bd.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Fm(e)===0)return null;let{title:n,href:o}=Nm(e),r=Om((e.textContent??"").trim())??Om(t.text)??"",s=BS(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:OS,scoreElement(e){return _m(e)},formatSummary(e,t){if(_m(e)===0)return null;let{title:n,href:o}=Nm(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
144
|
+
`)}}];function NS(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function FS(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??qm;return i==="simple"&&e.rules&&e.rules.length>0?(NS(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function Hd(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var _S=["data-testid","data-product","data-action","data-id","data-name","data-type"];function $S(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"||PS.has(t)||n&&RS.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Vm(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 jS(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Km(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Hd(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of _S){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${Hd(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=>Hd(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function US(e){return e==="static"?WS:IS}function Gm(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Km(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:$S(e),attributes:jS(e)}}function zS(e,t,n,o){let r=US(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 qS(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 VS(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if($m.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Vm(d)){i=a.nextNode();continue}let g=Gm(d,e.maxTextLength),b=g.text.length>0,f=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(S=>S==="role");if(!b&&!f){i=a.nextNode();continue}if(o.has(g.selector)){i=a.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=zS(d,g,e.rules,n);r.push({el:d,domIndex:s,enriched:g,score:x,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let g=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return g!==b?g-b:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;qS(p,d)||p.push(d)}return p.sort((d,c)=>{let g=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return g!==b?g-b:g===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let b=d.formattingRule.formatSummary(d.el,d.enriched,n);b&&(c=b)}let g={...d.enriched};return c&&(g.formattedSummary=c),g})}function KS(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let p=s,d=p.tagName.toLowerCase();if($m.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Vm(p)){s=r.nextNode();continue}let c=Gm(p,e.maxTextLength),g=c.text.length>0,b=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!g&&!b){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function GS(e={}){let t=FS(e),n=t.root??document.body;return n?t.mode==="simple"?KS(t,n):VS(t,n):[]}var al=100;function JS(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,al)}" (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,al)}" (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,al)}" (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,al)}"`);o.push(`Content:
|
|
155
155
|
${s.join(`
|
|
156
156
|
`)}`)}return o.join(`
|
|
157
157
|
|
|
158
|
-
`)}function
|
|
158
|
+
`)}function YS(){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 XS(){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 QS(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:jn(e.colors.primary,.95),100:jn(e.colors.primary,.9),200:jn(e.colors.primary,.8),300:jn(e.colors.primary,.7),400:jn(e.colors.primary,.6),500:e.colors.primary,600:jn(e.colors.primary,.8),700:jn(e.colors.primary,.7),800:jn(e.colors.primary,.6),900:jn(e.colors.primary,.5),950:jn(e.colors.primary,.45)}}),{...t,palette:n}}}}function ZS(){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 eT(){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 jn(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 tT(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var nT={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"}}},Jm={components:{panel:{borderRadius:"0",shadow:"none"}}},Ym={id:"shop",label:"Shopping Assistant",config:{theme:nT,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:xn},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"]}},Xm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Jm}},Qm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Jm}},Zm={shop:Ym,minimal:Xm,fullscreen:Qm};function oT(e){return Zm[e]}var rT=Bm;function Dd(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@${To}/dist`}function so(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function sT(e){if(e)return{getHeaders:so(e.getHeaders),onFeedback:so(e.onFeedback),onCopy:so(e.onCopy),requestMiddleware:so(e.requestMiddleware),actionHandlers:so(e.actionHandlers),actionParsers:so(e.actionParsers),postprocessMessage:so(e.postprocessMessage),contextProviders:so(e.contextProviders),streamParser:so(e.streamParser)}}var eh=`({ 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
|
+
}`,th=`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
|
+
}`,nh=`(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
|
+
}`,oh=`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
|
+
}`,aT=`(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
|
+
}`,iT=`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 rA(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: '${Ks(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&&Ao(o,"theme",e.theme," "),e.launcher&&Ao(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(...Hi(e," ")),o.push(...Bi(e," ",n)),o.push(...Di(e," ")),o.push(...Oi(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(${Qw}),`)),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(` ${Mg}`),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(` ${Mg}`),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(` ${kg}`),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(` ${kg}`),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 Rg(e){let t=Wi(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 sA(e,t){let n=Rg(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="${$c(t)}/install.global.js" data-config='${s}'></script>`}function aA(e,t){let n=t?.hooks,o=Wi(e),r=o!=="plain",s=$c(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: '${Ks(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&&Ao(a,"theme",e.theme," "),e.launcher&&Ao(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(...Hi(e," ")),a.push(...Bi(e," ",n)),a.push(...Di(e," ")),a.push(...Oi(e," ")),a.push(...jc(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 lT(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 il(e){return e.parserType??lT(e.streamParser)??"plain"}function ll(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 cl(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 dl(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 pl(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 ul(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Od(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 rh(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}: {`),rh(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Do(e,t,n,o){n&&(e.push(`${o}${t}: {`),rh(e,n,`${o} `),e.push(`${o}},`))}function Ca(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function cT(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:sT(n.hooks)}:void 0;return t==="esm"?dT(o,r):t==="script-installer"?gT(o,r):t==="script-advanced"?mT(o,r):t==="react-component"?pT(o,r):t==="react-advanced"?uT(o,r):fT(o,r)}function dT(e,t){let n=t?.hooks,o=il(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ca(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&&Do(s,"theme",e.theme," "),e.launcher&&Do(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(...pl(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(...ll(e," ")),s.push(...cl(e," ",n)),s.push(...dl(e," ")),s.push(...ul(e," ")),s.push(...Od(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 pT(e,t){let n=t?.hooks,o=il(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: '${Ca(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&&Do(s,"theme",e.theme," "),e.launcher&&Do(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(...pl(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(...ll(e," ")),s.push(...cl(e," ",n)),s.push(...dl(e," ")),s.push(...ul(e," ")),s.push(...Od(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 uT(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: '${Ca(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&&Do(o,"theme",e.theme," "),e.launcher&&Do(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(...pl(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(...ll(e," ")),o.push(...cl(e," ",n)),o.push(...dl(e," ")),o.push(...ul(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(${aT}),`)),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(` ${eh}`),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(` ${eh}`),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(` ${nh}`),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(` ${nh}`),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 sh(e){let t=il(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 p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(s.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function gT(e,t){let n=sh(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="${Dd(t)}/install.global.js" data-config='${s}'></script>`}function fT(e,t){let n=t?.hooks,o=il(e),r=o!=="plain",s=Dd(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: '${Ca(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&&Do(a,"theme",e.theme," "),e.launcher&&Do(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([i,p])=>{a.push(` ${i}: "${p}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"?a.push(` ${i}: ${p},`):typeof p=="number"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([i,p])=>{a.push(` ${i}: ${p},`)}),a.push(" },")),a.push(...pl(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(...ll(e," ")),a.push(...cl(e," ",n)),a.push(...dl(e," ")),a.push(...ul(e," ")),a.push(...Od(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 mT(e,t){let n=t?.hooks,o=sh(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 = '${Dd(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(${iT});`),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(` ${th}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${th}`),s.push(" ];")),s.push(""),n?.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(` ${oh}`),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(` ${oh}`),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: '${Ca(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 ah={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ih=.1,lh=.15,ch=1.5,Nd=24,dh=40,hT=`
|
|
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: ${Nd}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 yT(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=hT,document.head.appendChild(e)}function bT(e,t){let n=e.clientWidth-Nd*2-dh,o=e.clientHeight-Nd*2-dh;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function vT(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 xT(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");yT();let c=Math.max(0,Math.min(o,n.length-1)),g=r,b=s,f=null,x=1,C=!1,S=y("div","persona-dc-root"),M=y("div","persona-dc-toolbar"),P=y("div","persona-dc-toolbar-lead"),T=y("div","persona-dc-toolbar-trail"),L=lt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>$e(-1)}),H=y("div");H.style.position="relative";let O=y("button","persona-dc-title-btn");O.type="button",O.setAttribute("aria-expanded","false"),O.setAttribute("aria-haspopup","listbox");let _=y("span","persona-dc-title-text"),U=y("span","persona-dc-title-chevron"),z=se("chevron-down",12,"currentColor",2);z&&U.appendChild(z),O.append(_,U);let Y=y("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let A=!1;function G(){Y.innerHTML="";for(let ae=0;ae<n.length;ae++){let Re=n[ae],ct=y("button","persona-dc-dropdown-item");ct.type="button",ct.setAttribute("role","option"),ct.setAttribute("aria-current",ae===c?"true":"false");let et=y("span");if(et.textContent=Re.title,ct.appendChild(et),Re.description){let vt=y("span","persona-dc-dropdown-desc");vt.textContent=Re.description,ct.appendChild(vt)}ct.addEventListener("click",()=>{le(),Ve(ae)}),Y.appendChild(ct)}}function Q(){A=!A,Y.style.display=A?"":"none",O.setAttribute("aria-expanded",A?"true":"false"),A&&G()}function le(){A&&(A=!1,Y.style.display="none",O.setAttribute("aria-expanded","false"))}O.addEventListener("click",ae=>{ae.stopPropagation(),Q()});let J=()=>le();document.addEventListener("click",J),H.append(O,Y);let me=lt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>$e(1)}),ee=y("span","persona-dc-counter");P.append(L,H,me,ee);let ye=null;i&&(ye=Po({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:ae=>{g=ae,be.dataset.device=g,f=null,Le()}}),T.appendChild(ye.element));let Z=null;if(a){let ae=y("div","persona-dc-zoom-controls"),Re=lt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(lh,(f??x)-ih),Le()}});Z=y("span","persona-dc-zoom-level"),Z.title="Reset to 100%",Z.style.cursor="pointer",Z.addEventListener("click",()=>{f=1,Le()});let ct=lt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(ch,(f??x)+ih),Le()}}),et=lt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,Le()}});ae.append(Re,Z,ct,et),T.appendChild(ae)}if(p){let ae=y("div","persona-dc-separator");T.appendChild(ae);let Re=Po({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:b,onSelect:ct=>{b=ct,be.dataset.colorScheme=b,Be()}});T.appendChild(Re.element)}let ue=y("div","persona-dc-separator");T.appendChild(ue);let te=lt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});T.appendChild(te),M.append(P,T);let fe=y("div","persona-dc-stage"),be=y("div","persona-dc-iframe-wrapper");be.dataset.device=g,be.dataset.colorScheme=b;let he=y("iframe","persona-dc-iframe");he.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),he.setAttribute("loading","lazy"),he.title=n[c].title,be.appendChild(he),fe.appendChild(be),S.append(M,fe),e.appendChild(S);function Be(){try{let ae=he.contentDocument?.body;if(!ae)return;b==="dark"?ae.classList.add("theme-dark"):ae.classList.remove("theme-dark")}catch{}}he.addEventListener("load",()=>Be());function rt(){let ae=n[c];_.textContent=ae.title,ee.textContent=`${c+1} / ${n.length}`,he.title=ae.title}function $e(ae){let Re=((c+ae)%n.length+n.length)%n.length;Ve(Re)}function Ve(ae){ae<0||ae>=n.length||(c=ae,he.src=n[c].url,rt(),d?.(c,n[c]))}function Le(){if(C)return;let ae=ah[g]??ah.desktop;x=bT(fe,ae);let Re=Math.max(lh,Math.min(ch,f??x));vT(be,he,ae,Re,g),Z&&(Z.textContent=`${Math.round(Re*100)}%`)}let _e=new ResizeObserver(()=>Le());_e.observe(fe),rt(),he.src=n[c].url,requestAnimationFrame(()=>Le());function we(){C||(C=!0,_e.disconnect(),document.removeEventListener("click",J),S.remove())}return{element:S,goTo:Ve,next:()=>$e(1),prev:()=>$e(-1),getIndex:()=>c,setDevice(ae){g=ae,be.dataset.device=ae,ye?.setSelected(ae),f=null,Le()},setColorScheme(ae){b=ae,be.dataset.colorScheme=ae},setZoom(ae){f=ae,Le()},destroy:we}}export{ag as ASK_USER_QUESTION_CLIENT_TOOL,sg as ASK_USER_QUESTION_PARAMETERS_SCHEMA,ei as ASK_USER_QUESTION_TOOL_NAME,zr as AgentWidgetClient,Qs as AgentWidgetSession,Kr as AttachmentManager,pr as BrowserSpeechEngine,$g as DEFAULT_COMPONENTS,Ic as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,xn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Fg as DEFAULT_PALETTE,_g as DEFAULT_SEMANTIC,st as DEFAULT_WIDGET_CONFIG,Zm as PRESETS,Qm as PRESET_FULLSCREEN,Xm as PRESET_MINIMAL,Ym as PRESET_SHOP,Vr as ReadAloudController,gc as SUGGEST_REPLIES_CLIENT_TOOL,og as SUGGEST_REPLIES_PARAMETERS_SCHEMA,On as SUGGEST_REPLIES_TOOL_NAME,gC as THEME_ZONES,To as VERSION,Dn as WEBMCP_TOOL_PREFIX,Ns as WebMcpBridge,YS as accessibilityPlugin,XS as animationsPlugin,vm as applyFeaturePreferences,Gr as applyThemeVariables,Zr as attachHeaderToContainer,QS as brandPlugin,es as buildComposer,Sf as buildDefaultHeader,Ho as buildHeader,ga as buildHeaderWithLayout,Tf as buildMinimalHeader,zs as builtInClientToolsForDispatch,ln as canonicalArtifactDisplayMode,GS as collectEnrichedPageContext,Fn as componentRegistry,tl as createActionManager,Md as createAgentExperience,ub as createAskUserQuestionBubble,Sc as createBestAvailableVoiceProvider,Bw as createBubbleWithLayout,Sd as createCSATFeedback,Fc as createComboButton,sS as createComponentMiddleware,Cd as createComponentStreamParser,Mu as createDefaultSanitizer,xT as createDemoCarousel,Ay as createDirectivePostprocessor,mr as createDropdownMenu,yb as createFlexibleJsonStreamParser,lt as createIconButton,Mb as createImagePart,vc as createJsonStreamParser,Lo as createLabelButton,xd as createLocalStorageAdapter,Qa as createMarkdownProcessor,_r as createMarkdownProcessorFromConfig,Wf as createMessageActions,Td as createNPSFeedback,yc as createPlainTextParser,tT as createPlugin,bc as createRegexJsonParser,ud as createRovingTablist,LS as createSlashCommandsSource,ma as createStandardBubble,kS as createStaticMentionSource,lr as createTextPart,bi as createTheme,na as createThemeObserver,Po as createToggleGroup,ts as createTypingIndicator,dr as createVoiceProvider,sl as createWidgetHostLayout,xc as createXmlParser,rT as default,ls as defaultActionHandlers,el as defaultJsonActionParser,Id as defaultMentionFilter,qm as defaultParseRules,vi as detectColorScheme,Sy as directivePostprocessor,Us as ensureAskUserQuestionSheet,eo as escapeHtml,Ad as extractComponentDirectiveFromMessage,kb as fileToImagePart,JS as formatEnrichedContext,ir as generateAssistantMessageId,cT as generateCodeSnippet,Ab as generateMessageId,Km as generateStableSelector,Gs as generateUserMessageId,ur as getActiveTheme,Bc as getColorScheme,Tb as getDisplayText,Ef as getHeaderLayout,Eb as getImageParts,oT as getPreset,nl as hasComponentDirective,wc as hasImages,Zc as headerLayouts,eT as highContrastPlugin,Bm as initAgentWidget,vo as isAskUserQuestionMessage,rS as isComponentDirectiveType,Mt as isDockedMountMode,Ur as isSuggestRepliesMessage,pi as isVoiceSupported,or as isWebMcpToolName,hr as isWelcomeVisible,mc as latestAgentSuggestions,rw as listRegisteredStreamAnimations,Cu as loadMarkdownParsers,Su as markdownPostprocessor,ta as mergeWithDefaults,Sb as normalizeContent,rr as normalizeMediaType,Ds as onMarkdownParsersReady,xo as parseAskUserQuestionPayload,rg as parseSuggestRepliesPayload,hm as parseWidgetPreferenceSlice,Ys as pickBestVoice,Qi as pluginRegistry,ZS as reducedMotionPlugin,nw as registerStreamAnimationPlugin,ar as removeAskUserQuestionSheet,wd as renderComponentDirective,If as renderLoadingIndicatorWithFallback,se as renderLucideIcon,_u as resolveArtifactDisplay,to as resolveArtifactDisplayMode,Xi as resolveConfigPreferences,cn as resolveDockConfig,Os as resolveSanitizer,Wc as resolveTokens,Bo as resolveWelcomeConfig,ic as stripWebMcpPrefix,Hc as themeToCssVariables,ow as unregisterStreamAnimationPlugin,Lb as validateImageFile,jg as validateTheme};
|
|
479
480
|
//# sourceMappingURL=index.js.map
|